问题
I implemented an Android Application that consists of four activity (A,B,C,D).
A calls B; B calls C and C calls D.
The activity A implements a Handler
Handler handler=new Handler(){
public void handleMessage(Message msg){
Bundle bundle = new Bundle();
bundle = msg.getData();
String key = bundle.getString("Changed");
if(key.compareTo("NotificationType") == 0){
String completeStr = bundle.getString(key);
if(completeStr.compareTo("Message") == 0)
{
// update UI of Activity A
}
}
}
};
The Activity D can send a messagge using the hadler.
The question are:
What happens if the Activity A is in background when message is sent from Activity D?
What happens if the Activity A is destroyed before receiving the message through the handler?
回答1:
Use Custom BroadcastReceiver
Write this in ActivityD.java
Intent intent = new Intent();
intent.putExtra("message","hi");
intent.setAction("com.android.activity.SEND_DATA");
sendBroadcast(intent);
Write this in ActivityA.java
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Extract data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};
Updated
Now register Receiver
registerReceiver(mMessageReceiver,
new IntentFilter("com.android.activity.SEND_DATA"));
回答2:
To avoid issues you mentioned use Broadcast messaging system.
来源:https://stackoverflow.com/questions/16332713/android-updating-ui-using-handler