Android:了解如何使用一个具有多个操作的IntentService

时间:2013-02-17 19:21:34

标签: android intentservice

我有一个问题,即在特定活动流​​程下没有传递给IntentService的意图:这是场景:

  1. 考虑3个活动,Home,B和C.C有2个片段CF1和CF2。
  2. B,CF1和CF2使用相同的IntentService类,但操作不同。
  3. IntentService使用startService(Intent)开始。 (片段的getActivity()。startService(Intent))
  4. 无论IntentService何处开始,如果它在Activity / Fragment' s stopService(intent)中运行,我确保使用onStop()停止它。
  5. 如果活动流程为Home - > C - > CF1 - > CF2,一切正常。
  6. 如果活动流程为Home - > B - > C - > CF1 - > CF2,然后在CF2的startService(Intent)之后永远不会调用onHandleIntent。处理B和CF1意图。为了调试,我尝试等待IntentService在Activity B中完成,然后转到CF1 - > CF2,仍然是同样的问题。 CF1在启动相同的意向服务时似乎没有任何问题。当我尝试为CF2创建一个新的IntentService类时,它可以工作。
  7. 我的理解是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

    的代码完全相同

1 个答案:

答案 0 :(得分:6)

  

我的理解是......如果服务第一次运行,则调用onStartCommand(我们不应该为IntentService处理)。如果服务已在运行,则会为每次后续的startService调用调用onHandleIntent。

没有。每次onStartCommand()电话都会调用startService()。每onHandleIntent()startService()次调用都会调用IntentService,除非您在onStartCommand()中执行某些操作以更改正常行为。

  

IntentService使用startService(Intent)开始。

您使用IntentServicestartService()发送命令。

  

无论IntentService何处开始,我都会确保使用stopService(intent)

停止它

这是一个非常糟糕的主意。如the documentation中所述,IntentService所有startService()来电时,{{1}}将自行停止:

  

IntentService将接收Intents,启动工作线程,并根据需要停止服务。