I’d like to know how to pass data between a Service and an Activity without broadcastReceiver.
This is what I can’t make:
- I have a Service that periodically sends an intent via broadcast.
- I want to get the extras of this intent from an activity when I want, without wait a broadcast receiver.
I tried to use this code:
\\Service
String BROADCAST_ACTION = "ACTION";
Intent sendToUI = new Intent(BROADCAST_ACTION);
sendToUI.putExtra("key", "value");
sendBroadcast(sendToUI);
\\Activity
IntentFilter iF = new IntentFilter(MyService.BROADCAST_ACTION);
Intent intent = c.registerReceiver(null, iF);
Bundle extras = intent.getExtras();
if(extras != null){
String string = intent.getStringExtra("key");
}
But I get a nullpointerexception because intent is always null (I get nullpointerexception NOT in Bundle extras BUT IN Intent intent LINE).
In order to do this like this, the broadcast you send periodically has to “hang around” so that the activity can get it when it wants to.
In your service you need to send this broadcast as “sticky”, like this:
You must hold the BROADCAST_STICKY permission in order to use this API. If you do not hold that permission, SecurityException will be thrown.
EDIT: Add code for the Activity to read it:
Also, I’d suggest that you change the string you are using for `MyService.BROADCAST_ACTION” to include your fully qualified package name. This is because if you use just “ACTION”, there may be other applications that are also sending around sticky broadcasts with that action and you won’t be sure to get the one you intended (ie: the one sent by your service). Use something like this (in your service class):