How to update the UI of Activity from BroadCastReceiver

前端 未结 6 576
礼貌的吻别
礼貌的吻别 2020-12-03 22:57

I am learning Android concepts Activity and BroadCastReceiver. I want to update the content of Activity from the Br

6条回答
  •  囚心锁ツ
    2020-12-03 23:48

    try like this it may help you.

    Define this method in activity's oncreate method in which you want to update ui,

        BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
                    @Override
                    public void onReceive(Context context, Intent intent) {
                        //your code to update ui
                    }
                };
       LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("giveyourappname"));
    

    Define this action at place from where you want to update ui,

    try{
            ActivityManager am = (ActivityManager) this .getSystemService(ACTIVITY_SERVICE);
            List taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            Log.d("Activity", "Current Activity ::" + taskInfo.get(0).topActivity.getClassName());
            Log.d("Package", "Package Name :  "+ componentInfo.getPackageName());
    
            if(componentInfo.getPackageName().equals("your application package name")){
                 Intent intent = new Intent("giveyourappname");
                    //add data you wnat to pass in intent
                    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
            }
        }catch(Throwable e){
            e.printStackTrace();
        }
    

提交回复
热议问题