【发布时间】:2011-07-15 04:27:32
【问题描述】:
要从 Activiy 启动我的服务,我使用 startService(MyService.class)。这很好用,但在特殊情况下,服务应该以不同的方式启动。我想将一些参数传递给服务启动。
我在我的 Activity 中尝试了以下操作:
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() 中注册如下:
IntentFilter mControllerIntent = new IntentFilter("controller");
MyIntentReceiver mIntentReceiver= new MyIntentReceiver();
registerReceiver(mIntentReceiver, mControllerIntent);
使用此解决方案,服务启动但未收到意图。 如何启动服务并传递我的参数?
感谢您的帮助!
【问题讨论】:
-
MyIntentReceiver 有什么用?你想收听一些特定的广播并改变你的服务行为吗?
-
@Audrius:是的,你是对的。 MyIntentReceiver 用于更改我的服务的行为。我的服务有两种状态:一种是启动服务时,另一种是服务运行时。
标签: android parameters service android-activity