Android: Updating UI using Handler

倾然丶 夕夏残阳落幕 提交于 2019-12-12 09:27:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!