简体   繁体   中英

Android Service Activity Intent

I want to pass a string from activiy to service.

            Bundle mBundle = new Bundle();
            mBundle.putString("MyString", string);
            mIntent.putExtras(mBundle);
            startService(mIntent);

this is in Activity class

            Intent myIntent = getIntent();
            String value = myIntent.getExtras().getString(key);

and this is in Service class It doesn't accept getIntent() method :SI don't know what I'll do

服务中的代码必须放在onStart(Intent intent, int startid)方法中,并且代码变为String value = intent.getExtras().getString(key);

使用startService(mIntent)启动服务时,将startService(mIntent)服务的onStartCommand ,这是处理意图的好地方。

Move the part of your code that depends on the intent to onStartCommand: http://developer.android.com/reference/android/app/Service.html#onStartCommand(android.content.Intent , int, int)

OnStartCommand was called OnStart before api version 5, follow link to documentation for further information about backwards compatibility in your app.

@Override
  public int onStartCommand(Intent intent, int flags, int startId) {
      String value = intent.getExtras().getString(key);
  }

Also remember to move heavy code into a background thread that you start in onStartCommand, as otherwise you will run into an Application Not Responding error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM