我知道暂停一个线程很容易锁定UI,这通常是一个坏主意。但是我的理解是,如果某项服务作为不会导致任何问题的服务运行,因为服务将暂停,主应用程序将继续运行。
考虑到这一点,我要么做错了,要么误解了为MediaPlayer使用服务。
我创建了对象
public AudioService AudioService;
public boolean AudioServiceBound = false;
然后在我的SurfaceView的onStart事件中我绑定它:
public void onStart() {
Intent intent = new Intent(gameContext, AudioService.class);
gameContext.bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
}
在整个课程的其余部分,我运行的方法根据onResume和onPause事件暂停和恢复AudioService。
我试图为我的服务引入新功能。在我的主更新循环中,我运行下面的函数HalfOverSwitch()
:
public void HalfOverSwitch()
{
if (( ((float)player.getCurrentPosition()) / ((float)player.getDuration()) > 0.5) && !transitioning)
{
transitioning = true;
MediaPlayer temp = MediaPlayer.create(this, R.raw.dumped);
temp.setVolume(0, 0);
temp.setLooping(true);
temp.start();
for (int i = 0; i < 100; i++)
{
player.setVolume(100-i, 100-i);
temp.setVolume(i, i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
player = temp;
player.setVolume(100,100);
transitioning = false;
}
}
因为该函数没有返回任何内容并且在不同的线程中运行,所以我的理解是主要活动不会暂停。但它确实如此。这提出了一个问题,做出类似事情的最佳方法是什么,以及让我的AudioService成为服务(而不只是一个类)的重点是什么?
答案 0 :(得分:1)
服务在创建服务的同一个线程中运行。
http://developer.android.com/reference/android/app/Service.html
“请注意,服务与其他应用程序对象一样,在其托管进程的主线程中运行。这意味着,如果您的服务将进行任何CPU密集型(如MP3播放)或阻止(如网络)操作时,它应该生成自己的线程来完成这项工作。“