我是Android开发的新手,我需要一些小问题的帮助。
我有一个后台服务,该服务运行我的媒体播放器并与PlayerActivity通信。
到目前为止,一切都很好。
我需要安排在不同时期执行轨道。即,播放轨道x的时间比播放轨道y的30分钟等一分钟。
因此,我从PlayerActivity调用MyTimer线程,该线程在特定时间引发事件,
PlayerActivity捕获事件并调用MediaplayerService next()方法。
我的问题是,如果我在没有线程的情况下调用next(),它会很好地工作;如果在线程中进行调用,我会得到
mContext is null, can't getMirrorDisplayStatus!!!
带有Mediaplayer警告(1,902)
我试图通过Handler.post()和runOnUiThread()从PlayerActivity运行此线程
和我得到同样的错误。
下面是MyTimer线程的代码。
public class MyTimer implements Runnable {
private Object mPauseLock;
private boolean mPaused;
private boolean mFinished;
private TimeSection section;
public Trainer()
{
mPauseLock = new Object();
mPaused = false;
mFinished = false;
BusProvider.getInstance().register(this);
}
@Override
public void run()
{
while (!mFinished)
{
TimerManager tm = TimerManager.getInstace();
this.section = tm.getCurrentTimeSection();
if(this.section == null)
mFinished = true;
else
{
tm.inc();
// produce sectionChangeEvent event
BusProvider.getInstance().post(produceSectionEvent());
try
{
Thread.sleep((this.section.getTypeDuration() * 1000));
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
synchronized (mPauseLock)
{
while (mPaused)
{
try
{
mPauseLock.wait();
} catch (InterruptedException e)
{
}
}
}
}
}
/**
* Call this on pause.
*/
public void onPause() {
synchronized (mPauseLock) {
mPaused = true;
}
}
/**
* Call this on resume.
*/
public void onResume() {
synchronized (mPauseLock) {
mPaused = false;
mPauseLock.notifyAll();
}
}
@Produce public TimeSectionEvent produceSectionEvent(){
return new TimeSectionEvent(this.section);
}
}
玩家 Activity 的一些代码:
public class PlayerActivity implements
IMediaPlayerServiceClient{
private MediaPlayerService mService;
....
/**
* Binds to the instance of MediaPlayerService. If no instance of
* MediaPlayerService exists, it first starts a new instance of the service.
*/
public void bindToService()
{
Intent intent = new Intent(this, MediaPlayerService.class);
if (MediaPlayerServiceRunning())
{
// Bind to LocalService
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
} else
{
startService(intent);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
}
.....
/*
* This is how I start the timing thread
*/
private void startTiming()
{
mTimer = new MyTimer();
runOnUiThread(mTimer);
// trainingHandler.post(mTrainer);
}
public void next(TimeSection section)
{
mService.next(section);
}
/*
* Here I catch the TimeSectionEvent from MyTimer thread
*/
@Subscribe public void onSectionChanged(TimeSectionEvent e)
{
TimeSection section = e.getSection();
if(section != null)
next(section);
}
最佳答案
每个 Activity 都有上下文,因此从您所知的异常中我猜出它与MediaPlayerService的上下文有关。
您正在使用bindService(...)将意图绑定(bind)到应绑定(bind)上下文的MediaPlayerService。
尝试执行“mService.next(section);”时,尝试检查该绑定(bind)是否仍然存在