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 :S I don't kno开发者_StackOverflow中文版w what I'll do
The code in the service must be placed in onStart(Intent intent, int startid)
method and the code becomes String value = intent.getExtras().getString(key);
When you start the service using startService(mIntent)
the service's onStartCommand is called which is good place to handle the intent.
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.
精彩评论