问题
I want to change a TextView in the onReceive method of my BroadcastReceiver, but I can't access it with findViewById because it's not an activity. I don't want to create a private class for the BroadcastReceiver in my activity.
How can I get access?
回答1:
Define an interface and use a callback to let the activity know that a broadcast event has been received.
public Interface BroadcastReceiverListener {
void onReceive(int arg1, String arg2); ..<----add arguments you want to pass back
}
In your BroadcastReceiver class
ArrayList<BroadcastReceiveListener > listeners = new ArrayList<BroadcastReceiveListener >();
...
public void addBroadcastReceiveListener (BroadcastReceiveListener listener){
if(!listeners.contains(listener)){
listeners.add(listener);
}
}
public void removeBroadcastReceiveListener (BroadcastReceiveListener listener){
if(listeners.contains(listener)){
listeners.remove(listener);
}
}
In your OnReceive
for (BroadcastReceiveListener listener:listeners){
listener.onReceive(arg1, arg2);
}
In your Activity:
public class MyActivity extends Activity implements BroadcastReceiveListener {
...
broadcastReceiver.addBroadcastReceiveListener(this); <---- the instance of your receiver
...
}
public void onReceive(int arg1, String arg2){
// do whatever you need to do
}
Note. Because you use an interface, any class (not just an Activity) can implement it so you can update anywhere in your app. The BroadcastReceiver class doesn't know or care. It just calls the listeners, if any are registered.
Now, you don't need to access R, or anything to do with the UI since your Activity is the only class that knows about, and can change, your UI - which is the Android way!
[EDIT]
The arguments are whatever you need them to be.
Think of the Interface
as a contract. It says that anyone who implements it, must implement the onReceive()
method and that the method will be called with an integer and a String. It's up to you what arguments you need, if any.
BroadcastReceiver.onReceive()
calls the onReceive
callback of the interface and passes in the int and String as arguments.
You could change the Interface definition to pass a bool for example.
public Interface BroadcastReceiverListener {
void onReceive(boolean arg1); ..<----add arguments you want to pass back
}
Then your caller looks like this:
for (BroadcastReceiveListener listener:listeners){
listener.onReceive(someBooleanValue);
}
And your callback looks like this:
public void onReceive(boolean theCallerIsReady){
if(theCallerIsReady){
// do interesting stuff
}
}
来源:https://stackoverflow.com/questions/15029647/accessing-r-from-a-broadcastreceiver