I am using Android annotation library, and I want to pass data from service to activity using broadcast receiver. I want to utilize #Reciever of Android annotation, my attempt is same as this SO question
Any help is appreciated.
In your Activity, add this receiver method:
#Receiver(actions = "GPSLocationUpdates", local = true)
void receiveLocationUpdates() {
// TODO
}
And broadcast your Intent as usual from the Service:
Intent intent = new Intent("GPSLocationUpdates");
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
Related
I have a Service that scans for BLE devices. The Activity should show some data gathered by the Service.
A Receiver has been implemented, to be notified when the Bluetooth is enabled, so that we know when to start the Service.
If the Service is running, and the Activity is opened, it just executes bindService(). However, if the Service isn't running (because the Bluetooth is disabled), the App is opened and the Bluetooth is enabled, it won't bind because the binding process has already been skipped.
How can I be notified about the Service starting or automatically binding when started?
Thank you.
You can use the LocalBroadCastManager to send a broadCast from your service to your activity.
Helper to register for and send broadcasts of Intents to local objects within your process. This has a number of advantages over sending global broadcasts with sendBroadcast(Intent):
You can use localbroadcast reciever from your service.
In your service use these code
intent = new Intent("my-integer");
intent.putExtra("message",""+a);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
In your activity use this code
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Extract data included in the Intent
String data = intent.getStringExtra("message");
if (!data.equals("0")) {
//Do something
} else {
//Do something else
}
}
}
};
In my laboratory work I have to create a service, which sends notifications when speed of battery discharging is greater then set.
I created an Activity with EditText for this value and 2 button for starting and stopping the service. Also I created a BatteryService class, inherited form Service class and BatteryReciever.
Now reciver registers with action BATTERY_CHANGED in service in onStartCommand. And problem is how to pass data to reciever or how to know about events in service.
What is the best way to solve this task?
To trigger a BroadcastReceiver, you need to use
sendBroadcast(intent);
Put the data you want to send from the Service in the intent as follows:
Intent intent = new Intent("my.custom.action");
Bundle b = new Bundle();
b.putSerializable("name", name);
b.putShort("count", count);
intent.putExtra("bundle", b);
sendBroadcast(intent);
And retrieve the data in the onReceive() method of the BroadcastReceiver:
#Override
public void onReceive (Context context, Intent intent){
Bundle b = intent.getExtras();
// do awesome things ...
}
Try this. This will work.
I have some problems working with Android Services. I already have a Service which downloads a file from a server. (The Service checks cyclic for new data) Aftwerwards it parses the file and adds values to an ArrayList wich will be saved to SharedPreferences.
In my Activity there are two methods. One will display the values from the ArrayList/SharedPreferences in UI and the second method sets a Notification if needed.
But how do I now when my Service completed its task so the two methods can be started?
Register a BroadcastReceiver in your Activity something like:
myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// do my stuff
}
};
registerReceiver(myReceiver , new IntentFilter("com.myapp.DOWNLOADCOMPLETE"));
Then in your service send the broadcast:
Intent i = new Intent("com.myapp.DOWNLOADCOMPLETE");
sendBroadcast(i);
You can also putExtras on your intent if you need to pass some values:
Documentation BroadcastReceiver
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)?
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
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.
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.
I am trying to send a Broadcast from a service out to an Activity. I can verify the broadcast is sent from within the service, but the Activity doesn't pick up anything.
Here is the relevant service code:
Intent i = new Intent(NEW_MESSAGE);
i.putExtra(FriendInfo.USERNAME, StringUtils.parseBareAddress(message.getFrom()));
i.putExtra(FriendInfo.MESSAGE, message.getBody());
i.putExtra("who", "1");
sendBroadcast(i);
And the receiving end in the activity class:
public class newMessage extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if(action.equalsIgnoreCase(IMService.NEW_MESSAGE)){
Bundle extra = intent.getExtras();
String username = extra.getString(FriendInfo.USERNAME);
String message = extra.getString(FriendInfo.MESSAGE);
String who = extra.getString("who");
}
}
}
The BroadcastReceiver is defined within an Activity. I am registering the receiver in the onCreate method of the Activity, not in the Manifest file.
I'm stumped as to why it won't rec. anything.
Any insight?
EDIT
Registering takes place as follows:
registerReceiver(messageReceiver, new IntentFilter(IMService.NEW_MESSAGE));
Where "messageReceiver" is defined as
private newMessage messageReceiver = new newMessage();
IMService.NEW_MESSAGE is merely a string = "NewMessage"
I'm not sure if it is specific to the set up, or if it is a fix in general, but moving the register/unregister to the onResume/onPause _respectively_ and not registering in the onCreate solved the problem for me.
Try this two things:
Use manifest file to register receiver(but it barely helps)
Try make your Receiver a regular class, not inner one.
Inner class broadcast receiver will not be able to handle broadcast(means it unable to locate that class ).
So make it as a separate class
Definitely it will work.