问题
I have an activity that creates an intent, puts some extras with putExtra() and calls the startService(intent) to start a service.
This service calculates some stuff based on the extras and then I want to send the result back to the activity.
In which way can I do this?
I tried to create an intent on my service and broadcast it using sendBroadcast(). I have a broadcastReceiver on the activity but Im not sure if I register it correctly. Im confused!
Is there any other way to do so? Something like StartActivityForResult but for services (something like StartServiceForResult or something)?
回答1:
The method you are attempting to use is good! Without code though it will be hard to say what you might be doing incorrectly.
In your service you would broadcast an intent like this...
/**
* Send broadcast to the activity letting it know the service is active
*
* @param pActivate
*/
private final void sendServiceActiveBroadcast( final boolean pActivate ) {
final Intent _intent = new Intent();
_intent.setAction( "com.yourtld.android.SERVICE_BROADCAST" );
_intent.addCategory( "com.yourtld.android.CATEGORY" );
_intent.putExtra( "isactive", pActivate );
this.sendBroadcast( _intent );
}
then in your activity you could have something like...
Create an action string:
private static final String SERVICE_BROADCAST_ACTION = "com.yourtld.android.SERVICE_BROADCAST";
In your onResume() method you would have...
final IntentFilter serviceActiveFilter = new IntentFilter( SERVICE_BROADCAST_ACTION );
serviceActiveFilter.addCategory( "com.yourtld.android.CATEGORY" );
this.serviceReceiver = new BroadcastReceiver() {
@Override
public void onReceive( final Context context, final Intent intent ) {
if( intent != null ) {
if( intent.getBooleanExtra( "isactive", false ) ) {
// The service is active
} else {
// False...
}
}
}
};
this.registerReceiver( this.serviceReceiver, serviceActiveFilter );
Hope that helps
回答2:
You can do these three things which I know:
- You can create an Intent and put data in Intent and start that activity ----- bad Idea
- You can use SharedPreferences to pass the values -- only for primitive values
- You can use static variables ------ which I think the best way to pass from service.
Note: You can also use DB which is good if u have bulk of data.
回答3:
First, you can have the service send the intent directly to the activity. That way, even if the activity isn't currently running, it will be launched.
Second, you start the activity with FLAG_ACTIVITY_SINGLE_TOP
. This keeps the activity from launching if it's already running.
Third, you implement onNewIntent()
in your activity to catch any intents the service sends if your activity is already running.
来源:https://stackoverflow.com/questions/4823133/send-data-from-service-back-to-my-activity