【问题标题】:Android: start service with parameterAndroid:使用参数启动服务
【发布时间】: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


【解决方案1】:
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();
    }
}

【讨论】:

  • 也可以在服务类的onStartCommand方法中获取intent对象
  • 以及onHandleIntent(Intent intent)
【解决方案2】:

第 1 步:删除您的 BroadcastReceiver 实现。

第 2 步:检查您的服务在 onStartCommand() 中获得的 Intent,并查看通过 getAction() 执行的操作。

【讨论】:

  • 但这将只允许在 onCreate 之后更改服务。我想在onc​​reate中传递变量,然后怎么做
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-27
  • 1970-01-01
相关资源
最近更新 更多