我有一个问题,即在特定活动流程下没有传递给IntentService
的意图:这是场景:
startService(Intent)
开始。 (片段的getActivity()。startService(Intent))stopService(intent)
中运行,我确保使用onStop()
停止它。onHandleIntent
。处理B和CF1意图。为了调试,我尝试等待IntentService在Activity B中完成,然后转到CF1 - > CF2,仍然是同样的问题。 CF1在启动相同的意向服务时似乎没有任何问题。当我尝试为CF2创建一个新的IntentService
类时,它可以工作。我的理解是IntentService有一个意图队列。如果服务第一次运行,则调用onStartCommand(我们不应该为IntentService处理)。如果服务已在运行,则会为每次后续的startService调用调用onHandleIntent。
显然,我做错了什么但不清楚是什么。我试过调查其他stackoverflow问题,但没有帮助。我正在使用的代码非常简单:
的AndroidManifest.xml
<service android:name=".service.ExampleIntentService" />
活动B
@Override
public void onCreate(Bundle savedInstanceState)
{
.......
intent = new Intent(getApplicationContext(), ExampleIntentService.class);
intent.setAction(StringConstants.ACTION_B);
serviceRunning = true; //set to false in onReceiveResult
startService(intent);
}
@Override
public void onStop()
{
if(serviceRunning && intent != null)
stopService(intent)
}
片段CF1
@Override
public void onResume()
{
super.onResume();
intent = new Intent(getActivity(), ExampleIntentService.class);
intent.setAction(StringConstants.ACTION_CF1);
serviceRunning = true; //set to false in onReceiveResult
startService(intent);
}
@Override
public void onStop()
{
if(serviceRunning && intent != null)
stopService(intent)
}
片段CF2
的代码完全相同答案 0 :(得分:6)
我的理解是......如果服务第一次运行,则调用onStartCommand(我们不应该为IntentService处理)。如果服务已在运行,则会为每次后续的startService调用调用onHandleIntent。
没有。每次onStartCommand()
电话都会调用startService()
。每onHandleIntent()
次startService()
次调用都会调用IntentService
,除非您在onStartCommand()
中执行某些操作以更改正常行为。
IntentService使用startService(Intent)开始。
您使用IntentService
向startService()
发送命令。
无论IntentService何处开始,我都会确保使用stopService(intent)
停止它
这是一个非常糟糕的主意。如the documentation中所述,IntentService
所有startService()
来电时,{{1}}将自行停止:
IntentService将接收Intents,启动工作线程,并根据需要停止服务。