Android的:先从参数服务 [英] Android: start service with parameter
问题描述
要从Activiy我用 startService(MyService.class)
开始我服务。这个伟大的工程,但在特殊情况下,服务应该以不同的开始。我想一些参数传递给服务启动。
To start my service from an Activiy I use startService(MyService.class)
. This works great, but in a special case the service should be started differently. I want to pass some parameters to the service start.
我想在我的活动如下:
Intent startMyService= new Intent();
startMyService.setClass(this,LocalService.class);
startMyService.setAction("controller");
startMyService.putExtra(Constants.START_SERVICE_CASE2, true);
startService(startMyService);
在我的服务我使用:
public class MyIntentReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("controller"))
{
// Intent was received
}
}
}
在IntentReceiver注册在的onCreate()是这样的:
The IntentReceiver is registered in onCreate() like this:
IntentFilter mControllerIntent = new IntentFilter("controller");
MyIntentReceiver mIntentReceiver= new MyIntentReceiver();
registerReceiver(mIntentReceiver, mControllerIntent);
通过此解决方案的服务启动,但意图不是接收。 我如何开始一个服务,并通过我的参数?
With this solution the service starts but the intent is not received. How can I start a Service and pass my parameters?
感谢您的帮助!
推荐答案
步骤#1:删除你的的BroadcastReceiver
实施
Step #1: Delete your BroadcastReceiver
implementation.
第2步:检查意图
您服务获取 onStartCommand()
通过,并期待在动作的getAction()
。
Step #2: Examine the Intent
your service gets in onStartCommand()
and look at the action via getAction()
.
这篇关于Android的:先从参数服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!