我有一个问题,意图没有被传递到IntentService
特定活动流下:这是场景:
- 考虑 3 个活动,Home、B 和 C。C 有 2 个片段 CF1 和 CF2。
- B、CF1 和 CF2 使用相同的 IntentService 类,但动作不同。
- IntentService 开始使用
startService(Intent)
. (getActivity().startService(Intent) 用于片段) - 无论 IntentService 在哪里启动,我都会确保它
stopService(intent)
在 Activity/Fragment 中运行时停止使用onStop()
。 - 如果活动流程是 Home -> C -> CF1 - >CF2,则一切正常。
- 如果活动流是 Home -> B -> C -> CF1 -> CF2,则
onHandleIntent
在从 CF2 的 startService(Intent) 之后永远不会调用。处理 B 和 CF1 意图。为了调试,我尝试在Activity B中等待IntentService完成,然后转到CF1 -> CF2,仍然是同样的问题。CF1 在启动相同的意图服务时似乎从来没有任何问题。当我尝试IntentService
为 CF2 创建一个新类时,它起作用了。
我的理解是 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