I'm having a problem with sending a broadcast from a Service to an activity.
This is what I have in my Service class:
Intent intent = new Intent();
intent.setAction(BROADCAST_ACTION);
sendBroadcast(intent);
I have many Activities and in one of my activities I have this:
class MyBroadcast extends BroadcastReceiver {
#Override
public void onReceive(Context ctxt, Intent i) {
System.out.println("received");
}
};
The problem I have is that my broadcast receiver doesn't receive anything!!
Help!
EDIT:
If I have many activities how can send a broadcast message to all of them. In other words can I apply the same broadcast receiver to all the activities !?
Like others said, you need to register the activity first to receive those broadcasts (see Flo's answer)
For your other quesition (re: EDIT). If you are taking the same action, you should create an overall Activity, and have your other activities extend that activity..
Then in this super class, implement the broadcast receiver registers on onResume and un register onStop..
You have to register the broadcast receiver before it can receive anything.
Have a look at this question.
Related
When I am working with broadcast receivers, I get a little confused about methods like sendBroadcast and registerReciever. Both gives the same result, and working functionality are also the same. But, what is the reason behind to work with both?
For example, If I try to get the result of my battery level, I am using the coding like
public void onButtonClick(View view)
{
IntentFilter intentFilter=new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
BraodcastReceiver br=new BroadcastReceiver();
registerReceiver(br,intentFilter);
}
or
public void onButtonClick(View view)
{
Intent intent=new Intent(Intent.ACTION_BATTERY_CHANGED);
sendBroadcast(intent);
}
What are the differences between this two methods? How they will work? Can you please give me the reasons?
My BroadcastReceiver class:
public class MyBroadcastClass extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
int level= intent.getIntExtra(BatteryManager.EXTRA_LEVEL,0);
Log.d("BatteryLevel",level);
}
}
First of all you have to understand what is broadcast receiver in android.
This one example
I will explain shortly.
The first example is registering as the name indicates. So after registering a particular broadcast , it will listen for any broadcast with that ACTION you provided with intentFilter. The working is same as the callback mechanism.
The second example is sending broadcast . Sending broadcast means you broadcast something, say battery change(OS Level) ,It will broadcast with an ACTION.
SO send broadcast will send some data with Action , if we listen a broadcast with Action then it will trigger on BroadcastRecicver class
I suggest you to go through the developer docs https://developer.android.com/reference/android/content/BroadcastReceiver.html
you will get the clear idea.
coming to your question
registerReceiver() is used to register your broadcast receiver to a particular action eg- Intent.ACTION_BATTERY_CHANGED or you can define your own.
What it mean is that whenever any APP will send a broadcast (send using a sendBroadcast() method) to this action your broadcast receivers onReceive() method will get called.
So I have broadcast receiver that is getting started on boot. I have an activity that using the information being collected by the broadcast receiver. I want the activity to be able to update its recycler view every time the broadcast receiver is called, the problem is the activity has no reference to the broadcast receiver. Is there a way that I can have my activity listen for the broadcasts and update itself?
The only thing I can think of is having the activity run a repeating task that will try to update itself with new information. This doesn't seem like a good solution to me.
the best approach is to register a BroadcastReceiver - see documentation on this. In your case you'd want to Programmatically register a broadcast receiver so that the onReceive(Context context, Intent intent) from inside the Activity class. In this way, you can then update the Recyclerview as you desire. Something like:
public void onCreate(Bundle savedInstanceState){
...
IntentFilter filter = new IntentFilter();
//you may want to set whatever filters here...
//define the broadcast receiver
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//here you can update the RecyclerView as you desire using intent's data
}
};
//register the broadcast receiver
registerReceiver(receiver, filter);
}
I strongly recommend that you go through this nice BroadcastReceiver tutorial.
Enjoy.
The broadcast receiver registered for BOOT_COMPLETED action has nothing to do with the activity, it's a separate component. So, yes, you don't have a reference to your activity and you should not run any periodical task.
What I would do is to write the collected data to the database or shared preferences and then read it when your activity is actually on the screen.
If you use an SQLite database you can use a ContentObserver to notify your activity about changes to the underlying data. This works great with loaders.
In case of shared preferences you can use a OnSharedPreferenceChangeListener registered in your activity.
Hi I am developing android application in which I am defining one broadcast receiver.I am calling receiver from my activity. I am defining broadcast receiver like this :
public class MyScheduleReceiver extends BroadcastReceiver {
private static final long REPEAT_TIME = 100 * 5;
#Override
public void onReceive(Context context, Intent intent) {
Log.i("RRRRRRRRRRRRRRRRRRRRRRRR", "on receive");
}
}
In android manifest file I am defining like this:
<receiver android:name="abc.xyz.MyScheduleReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
and in main activity I am calling my broadcast receiver like this :
//in activity oncreate
startService(new Intent(this, MyScheduleReceiver.class));
My problem is that when call start service it's not starting my service actually. But when i restart my device it start my service because I gave intent filter "BOOT_COMPLETED". what I wanted to do actually when i call start service my service must be start,
Am I doing something wrong. How to solve this problem?
Actual what happens here is that you can staring a broadcast receiver while starting the activity and this broadcast receiver starts listening BOOT_COMPLEATED is happening or not. When this happens it comes to onreceive . If you need to start a process doing in background you can use a a Service insted of BroadcastReciever. BroadcastRecievers are used to listen for some events to happen.Go through this, it will help you
Services
BroadcastReceiver
You're either confused, or you aren't wording your question well. What you have in your manifest (and how Android works generally) is that when BOOT_COMPLETED occurs, it will call that BroadcastReceiver you defined. It will not automatically start an activity or service. If you want to do that, you need to call startService or startActivity in your onReceive function of the receiver.
You do not start BroadcastReceivers. You start services, which are long term background processes. You register BroadcastReceivers to be informed of special events (like BOOT_COMPLETED). When one of the events you registered for occurs, it will create an instance of that class and call its onReceive.
Hopefully that clears things up. If not, I suggest you reread some tutorials on services and broadcast receivers, you seem to have the two confused.
startService call would only start a Service. MyScheduleReceiver here is a braodcast receiver. To trigger broadcast receivers, you generally have to send broadcasts and not call the startService.
to start broadcasts you need to send broadcasts not startService()
add this instead of startService(new Intent(this, MyScheduleReceiver.class));
Intent intent = new Intent();
intent.setAction("pakagename.MyScheduleReceiver");
sendBroadcast(intent);
I hope it helps.
So I understand (I think) about broadcast intents and receiving messages to them.
So now, my problem/what I can't work out is how to send a message from the onReceive method of a receiver to an activity. Lets say I have a receiver as such:
public class ReceiveMessages extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if(action.equalsIgnoreCase(TheService.DOWNLOADED)){
// send message to activity
}
}
}
How would I send a message to an activity?
Would I have to instantiate the receiver in the activity I want to send messages to and monitor it somehow? Or what? I understand the concept, but not really the application.
Any help would be absolutely amazing, thank you.
Tom
EDITED Corrected code examples for registering/unregistering the BroadcastReceiver and also removed manifest declaration.
Define ReceiveMessages as an inner class within the Activity which needs to listen for messages from the Service.
Then, declare class variables such as...
ReceiveMessages myReceiver = null;
Boolean myReceiverIsRegistered = false;
In onCreate() use myReceiver = new ReceiveMessages();
Then in onResume()...
if (!myReceiverIsRegistered) {
registerReceiver(myReceiver, new IntentFilter("com.mycompany.myapp.SOME_MESSAGE"));
myReceiverIsRegistered = true;
}
...and in onPause()...
if (myReceiverIsRegistered) {
unregisterReceiver(myReceiver);
myReceiverIsRegistered = false;
}
In the Service create and broadcast the Intent...
Intent i = new Intent("com.mycompany.myapp.SOME_MESSAGE");
sendBroadcast(i);
And that's about it. Make the 'action' unique to your package / app, i.e., com.mycompany... as in my example. This helps avoiding a situation where other apps or system components might attempt to process it.
No offense, but your question is still damn vague. So, I'm going to outline a whole mess of scenarios and hope that one of them actually hits whatever problem you think you have.
Scenario A: Only The Activity
If you only need to receive the broadcast when you have an activity in the foreground, have the activity register the BroadcastReceiver using registerReceiver(). As #MisterSquonk indicated, you would register the receiver in onResume() and unregister it in onPause().
Scenario B: Activity If In Foreground, Else Other; Ordered Broadcast
If you want the foreground activity to handle the broadcast, but you want something else to happen if that activity is not in the foreground (e.g., raise a Notification), and the broadcast is an ordered broadcast (e.g., incoming SMS), then you would still use the Scenario A solution, but with a higher-priority IntentFilter (see setPriority()). In addition, you would register a BroadcastReceiver via a <receiver> element in the manifest, with a lower-priority <intent-filter> for the same broadcast. In the activity's BroadcastReceiver, call abortBroadcast() to consume the event and prevent it from reaching your manifest-registered BroadcastReceiver.
Scenario C: Activity If In Foreground, Else Other; Regular Broadcast
If Scenario B almost fits, but the broadcast you are listening for is not an ordered broadcast, you will need to start with Scenario B. However, have the broadcast that both receivers have in their respective filters be one of your own, using a private action string as #MisterSquonk suggested. In addition, have another BroadcastReceiver registered in the manifest, whose <intent-filter> is for the real broadcast you're listening for. That receiver would simply call sendOrderedBroadcast() to send out the ordered broadcast that the other receivers are listening on.
Scenario D: Activity Regardless of Foreground
If some activity of yours needs to know about the broadcast, and it does not matter whether or not it is in the foreground, you need to rethink what you mean by that. Usually, this really means that the broadcast affects your data model in some way, in which case your concern should not be to let the activities know, but rather to update your data model, and use your already-existing "let the activities know about the data model change" logic handle the rest.
If, however, you are convinced that this is not part of your data model, you can implement Scenario B or Scenario C, plus stick some information in a static data member. Your activities can examine that static data member in onResume() to pick up the information about the broadcast when they return to the foreground.
If you're thinking "but, what if my process is terminated between the broadcast and the other activity coming to the foreground?", then your broadcast really is updating your data model, per the opening paragraph of this scenario.
If you're thinking "but, I want to update an activity that is doing work in the background", then the activity in question is broken. Activities should never be doing work in the background. That work should be delegated to some form of service, and there's a whole related set of scenarios for getting a broadcast to the service.
To broadcast an intent:
Intent intent = new Intent("com.yourcompany.testIntent");
intent.putExtra("value","test");
sendBroadcast(intent);
To receive the same intent use:
IntentFilter filter = new IntentFilter("com.yourcompany.testIntent");
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String value = intent.getExtras().getString("value");
}
};
registerReceiver(receiver, filter);
Possibly not relevant at the time of the question being asked but there is now the LocalBroadcastManager in the Android Support Package.
Works pretty much the same way as normal broadcasts but all "chatter" is local to the app it is running in.
Advantages:
You know that the data you are broadcasting won't leave your app, so don't need to worry about leaking private data.
It is not possible for other applications to send these broadcasts to your app, so you don't need to worry about having security holes they can exploit.
It is more efficient than sending a global broadcast through the system.
Example:
Intent i = new Intent("my.local.intent");
LocalBroadcastManager.getInstance(context).sendBroadcast(i);
and to receive
receiver = new MyBroadcastReceiverToHandleLocalBroadcast();
IntentFilter i = new IntentFilter();
i.addAction("my.local.intent");
LocalBroadcastManager.getInstance(context).registerReceiver(receiver, i);
I want to know whether an app can be a BroadcastReceiver and sender? Please expain with an example.
Application can't be a BroadcastReceiver. BroadcastReceiver is an application component. But answer to your question is yes: you can send broadcasts from one component and receive it in another.
For ex. in activity:
Intent intent = new Intent(...);
sendBroadcast(intent);
In receiver:
#Override
public void onReceive(Context context, Intent intent) {
// here is your intent
}
Yes, it can. An example can be found here.
If by app you mean activity, so yes you can but you will have to embed your BroadcastReceiver in your activity and register/unregister it yourself. That way, you just need to add your activity as Activity in the Manifest and you activity will be able to receive a broadcast and send broadcast as well.
I m not too sure how it behaves in term of life cycle though. You will need to look it up if it s what you want.