gpt4 book ai didi

android - IntentService 没有启动

转载 作者:行者123 更新时间:2023-11-30 02:43:10 33 4
gpt4 key购买 nike

我的 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,我将它保存在我的 Application 中以减少对象实例化。这个想法是,一旦应用程序失去焦点,媒体播放器就会播放。但是,该服务永远不会被触发。

下面是我从 FragmentonStop() 调用服务的方式

showMediaPlayerNotification();
Intent music = new Intent(getActivity(), MusicService.class);
getActivity().startService(music);

我也在 list 中声明了它。 logcat也没有报错。

这是怎么回事?

更新 1:

Once you call startService(), the IntentService does the work defined in its onHandleIntent() method, and then stops itself.

是不是服务自己停止了,因为它只是执行了一行?
我应该将媒体播放器移动到线程吗?

更新 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();
}
//------------------------------------------------------------------------------
}

关于android - IntentService 没有启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25472615/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com