Android:使用参数启动服务

Mik*_*ike 20 parameters service android android-activity

从Activiy开始我的服务我使用startService(MyService.class).这很好用,但在特殊情况下,服务应该以不同的方式启动.我想将一些参数传递给服务启动.

我在我的活动中尝试了以下内容:

Intent startMyService= new Intent();
startMyService.setClass(this,LocalService.class);
startMyService.setAction("controller");
startMyService.putExtra(Constants.START_SERVICE_CASE2, true);

startService(startMyService);
Run Code Online (Sandbox Code Playgroud)

在我的服务中我使用:

public class MyIntentReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals("controller")) 
        {
                // Intent was received                               
        }

    }
} 
Run Code Online (Sandbox Code Playgroud)

IntentReceiver在onCreate()中注册如下:

IntentFilter mControllerIntent = new IntentFilter("controller");
MyIntentReceiver mIntentReceiver= new MyIntentReceiver();
registerReceiver(mIntentReceiver, mControllerIntent);
Run Code Online (Sandbox Code Playgroud)

使用此解决方案,服务启动但未收到意图.如何启动服务并传递参数?

谢谢你的帮助!

Dee*_*rma 26

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 您还可以在服务类的onStartCommand方法中获取intent对象 (3认同)

Com*_*are 15

第1步:删除您的BroadcastReceiver实施.

步骤2:检查Intent您的服务进入onStartCommand()并通过查看操作getAction().

  • 但这只允许在onCreate之后更改服务.我想在onc​​reate中传递变量,然后如何做到这一点 (3认同)