Android IntentService未启动
我的Android IntentService未启动,android,android-mediaplayer,intentservice,Android,Android Mediaplayer,Intentservice,我的IntentService如下所示: public class MusicService extends IntentService{ final static String NAME = "MusicService"; //------------------------------------------------------------------------------ public MusicService(String name) {
IntentService
如下所示:
public class MusicService extends IntentService{
final static String NAME = "MusicService";
//------------------------------------------------------------------------------
public MusicService(String name) {
super(NAME);
}
//------------------------------------------------------------------------------
public MusicService() {
super(NAME);
}
//------------------------------------------------------------------------------
@Override
protected void onHandleIntent(Intent intent) {
// Toast never comes up
Toast.makeText(getApplicationContext(), NAME, Toast.LENGTH_SHORT).show();
PodcastrApplication.newInstance().getMediaPlayer().start();
}
//------------------------------------------------------------------------------
}
我在应用程序中保留了一个MediaPlayer
,以减少对象实例化。这个想法是,一旦应用程序失去焦点,媒体播放器就会播放。但是,该服务从未启动。
下面是我如何从我的片段的onStop()调用服务
showMediaPlayerNotification();
Intent music = new Intent(getActivity(), MusicService.class);
getActivity().startService(music);
我也在舱单上声明过。logcat中也没有错误
发生了什么事
更新1:
<service
android:name=".service.MusicService"
android:enabled="true"
android:exported="false" />
调用startService()后,IntentService将执行定义的工作
在其onHandleIntent()方法中,然后停止自身
服务是否因为只是一行执行而停止自身?
我应该将媒体播放器移动到线程吗
更新2:
<service
android:name=".service.MusicService"
android:enabled="true"
android:exported="false" />
您在后台线程中调用了Toast.makeText()
!,任何UI内容都必须在UI线程中完成
注意:IntentService
使用后台线程,而Service
使用UI线程
您可以尝试:
public class MusicService extends IntentService{
Handler mHandler;
final static String NAME = "MusicService";
//------------------------------------------------------------------------------
public MusicService(String name) {
super(NAME);
mHandler = new Handler();
}
//------------------------------------------------------------------------------
public MusicService() {
super(NAME);
mHandler = new Handler();
}
//------------------------------------------------------------------------------
@Override
protected void onHandleIntent(Intent intent) {
mHandler.post(new Runnable{
@Override
public void run(){
Toast.makeText(getApplicationContext(), NAME, Toast.LENGTH_SHORT).show();
}
});
// Toast never comes up
PodcastrApplication.newInstance().getMediaPlayer().start();
}
//------------------------------------------------------------------------------
}
我甚至在这里看了一眼:那么,我怎么知道我的服务是否真的开始了呢?:)@LittleChild一个简单的方法是放置Log.d(…)
,然后检查控制台!