安卓:带参数启动服务

27

我想通过startService(MyService.class)从一个Activity启动我的服务,这很好用。但在某些特殊情况下,我希望以不同的方式启动服务,即传递一些参数给服务。

我在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                               
        }

    }
} 

在onCreate()中注册IntentReceiver,像这样:

IntentFilter mControllerIntent = new IntentFilter("controller");
MyIntentReceiver mIntentReceiver= new MyIntentReceiver();
registerReceiver(mIntentReceiver, mControllerIntent);

使用这个解决方案,服务已经启动但意图没有被接收到。我该如何启动服务并传递我的参数?

谢谢你的帮助!

通过这个解决方案,您可以启动服务,但是无法接收到意图。 如何启动服务并传递参数?

感谢您的帮助!


MyIntentReceiver是做什么用的?您想要监听某些特定的广播并更改您的服务行为吗? - Audrius
@Audrius:是的,你说得对。MyIntentReceiver 用于改变我的服务的行为。我的服务有两种状态:一种是启动服务时,另一种是服务正在运行时。 - Mike
2个回答

33
Intent serviceIntent = new Intent(this,ListenLocationService.class); 
serviceIntent.putExtra("From", "Main");
startService(serviceIntent);
//and get the parameter in onStart method of your service class

@Override
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);
    Bundle extras = intent.getExtras();

    if(extras == null) {
        Log.d("Service","null");
    } else {
        Log.d("Service","not null");
        String from = (String) extras.get("From");
        if(from.equalsIgnoreCase("Main"))
            StartListenLocation();
    }
}

3
在Service类的onStartCommand方法中,您也可以获取意图对象。 - Deepak Sharma
1
以及在 onHandleIntent(Intent intent) 中。 - grim

15

步骤#1:删除您的BroadcastReceiver实现。

步骤#2:检查onStartCommand()中服务接收到的Intent,并通过getAction()查看操作。


6
但这样只允许在onCreate之后更改服务。如果我想在onCreate中传递变量,应该怎么做? - Santhosh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接