Android:理解使用一个IntentService和多个操作
在特定的活动流下,我的意图无法传递给Android:理解使用一个IntentService和多个操作,android,intentservice,Android,Intentservice,在特定的活动流下,我的意图无法传递给IntentService:这是一个场景: 考虑3个活动,Home、B和C。C有2个片段CF1和CF2 B、 CF1和CF2使用相同的IntentService类,但具有不同的操作 IntentService是使用startService(Intent)启动的。(getActivity().startService(Intent)用于片段) 无论IntentService在何处启动,如果它在Activity/Fragment的onStop()中运行,我都会使用
IntentService
:这是一个场景:
startService(Intent)
启动的。(getActivity().startService(Intent)用于片段)onStop()
中运行,我都会使用stopService(intent)
确保它停止onHandleIntent
。B和CF1意图得到处理。对于调试,我尝试在活动B中等待IntentService完成,然后转到CF1->CF2,仍然是相同的问题。在启动相同意图的服务时似乎从来没有任何问题。当我尝试为CF2创建一个新的IntentService
类时,它成功了<service android:name=".service.ExampleIntentService" />
片段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完全相同
我的理解是。。。如果服务是第一次运行,则会调用onStartCommand(我们不应该为IntentService处理该命令)。如果服务已在运行,则会为startService的每个后续调用调用OnHandleContent
否。onStartCommand()
是为每个startService()
调用调用的<除非您在onstart命令()
中执行某些操作以更改正常行为,否则每次调用IntentService()
时都会调用code>onHandleIntent()
IntentService使用startService(Intent)启动
您可以使用startService()
向IntentService
发送命令
无论IntentService在哪里启动,我都会使用stopService(intent)确保它停止
这是一个非常糟糕的主意IntentService
将在处理完所有startService()
调用后自动停止,如中所述:
IntentService将接收意图,启动工作线程,并根据需要停止服务
IntentService不会将Intent排队。为每个入站目的调用startService;所有调用都在服务本地的循环器线程上排队。当服务不做任何事情时停止服务,这是一种很好的做法,它只是一种优化。我建议您在应用程序正常运行之前停止使用它properly@G.BlakeMeike我不理解“不排队意图”和“调用在服务本地的循环线程上排队”之间的区别。我会试着打电话给stopService看看。但是仅仅创建一个单独的intentService会更好吗?我知道那会有用的。编辑:我也不确定为什么我没有看到片段CF1有同样的问题。区别在于意图总是传递给IntentService.startService。startService方法使本地队列上的调用排队,另一个线程从该队列中退出调用,并将其作为调用传递给onHandleIntent。都是。请看下面马克的回答:停止呼叫stopService。比如@G.BlakeMeike,你说,我试着删除stopService,结果成功了。但是,当用户离开一个运行着IntentService的活动时,我仍然不确定正确的方法是什么。你说这是个坏主意,如果用户离开活动,我们不应该停止服务吗?@Prasanna:使用
IntentService
的原因是,如果用户离开活动,你希望工作继续进行。如果您不想这样做,请不要使用IntentService
——只需使用线程即可。
@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)
}