How to update the UI of Activity from BroadCastReceiver

前端 未结 6 571
礼貌的吻别
礼貌的吻别 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:39

    Squonk-s answer only works, if the Activity is active currently. If you dont want to declare / define your BroadcastReceiver (BR) in an other Activity, or if you want to make some changes even if the app is not foreground, than your solution would look something like this.

    First, you declare the BR, and save, or override the data needed to show in Acitvity.

    public class MyBR extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            // override the data. Eg: save to SharedPref
        }
    }
    

    Then in Activity, you show the data

    TextView tv = findViewById(R.id.tv);
    tv.setText(/*get the data Eg: from SharedPref*/);
    

    And you should use a Timer to refresh the tv as well:

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                     public void run() {
                        TextView tv = findViewById(R.id.tv);
                        tv.setText(/*get the data Eg: from SharedPref*/);
                    }
                });
            }
        }, REFRESH_RATE, REFRESH_RATE);
    

    REFRESH_RATE could be something like 1 second, but you decide.

提交回复
热议问题