Android Best Practice on Updating the UI from BroadcastReceiver to a certain activity

╄→гoц情女王★ 提交于 2019-11-28 04:23:36

The easiest way to provide this functionality is to put the broadcast receiver in you Activity and bind / unbind it using registerReceiver and unregisterreceiver:

public class MyActivity extends Activity {
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            MyActivity.this.receivedBroadcast(intent);
        }
    };
    @Override
    public void onResume() {
        super.onResume();
        IntentFilter iff = new IntentFilter();
        iff.addAction("android.intent.action.MEDIA_BUTTON");
        // Put whatever message you want to receive as the action
        this.registerReceiver(this.mBroadcastReceiver,iff);
    }
    @Override
    public void onPause() {
        super.onPause();
        this.unregisterReceiver(this.mBroadcastReceiver);
    }
    private void receivedBroadcast(Intent i) {
        // Put your receive handling code here
    }
}

Depending on the intent you wish to receive, you may need to add the appropriate permissions to your AndroidManifest.xml file.

What I recently had to do to change a Button's text after receiving data from a LocalBroadcastManager is to store the value in a private field and then do the UI stuff in my onResume() method.

public class myClass extends Activity {

    private String myString;

    @Override
    public void onCreate(Bundle savedInstanceState) {       
        super.onCreate(savedInstanceState);         
        // register to receive data
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(receiver, new IntentFilter("myAction"));      
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // get the extra data included in the intent
            myString = intent.getStringExtra("myString");   
        }
    };

    @Override   
    public void onResume() {
        super.onResume();
        System.out.println("onResume");
        // do something to the UI
        myButton.setText(myString != null ? myString : "Default");  
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!