Send data from the service back to my activity

I have an activity that creates an intent, adds some additional functions with putExtra (), and calls startService (intent) to start the service.

This service calculates some things based on additional functions, and then I want to send the result back to this activity.

How can i do this?

I tried to create an intent for my service and broadcast it using sendBroadcast (). I have a broadcastReceiver, but I'm not sure if I will register it correctly. I am embarrassed!

Is there any other way to do this? Something like StartActivityForResult, but for services (something like StartServiceForResult or something else)?

+4
source share
3 answers

The method you are trying to use is good! Without code, although it will be hard to say what you can do wrong.

In your service you will broadcast such an intention ...

/** * 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 be something like ...

Create an action line:

 private static final String SERVICE_BROADCAST_ACTION = "com.yourtld.android.SERVICE_BROADCAST"; 

In your onResume () method you will 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

+5
source

You can do these three things that I know:

  • You can create an intent and put the data in the Intent and start this activity ----- bad Idea
  • You can use SharedPreferences to pass values ​​- only for primitive values
  • You can use static variables ------, which, I think, is the best way to switch from service.

Note: You can also use a database that is good if you have a large amount of data.

0
source

Firstly, you can send the service directly to the action. Thus, even if this activity is not already running, it will be running.

Secondly, you get started with FLAG_ACTIVITY_SINGLE_TOP . This causes the activity to start if it is already running.

Thirdly, you implement onNewIntent() in your activity in order to catch any intentions that the service sends if your activity is already running.

0
source

Source: https://habr.com/ru/post/1337404/


All Articles