views:

143

answers:

1

When i have a broadcastReceiver say android.intent.action.MEDIA_BUTTON and i want to update the current activity's UI without creating a new activity, is there any good practice on this one?

What i know (might not be correct)

1) I can put the BroadcastReceiver in the same class as the activity and call the updateUI function after certain activity

2) Create a ContentObserver?

3) Communicate to a service created by the activity, use aidl. (I dont know how to get the current service if its registered from an activity)

4) Create a custom filter on the broadcastReceiver located on the same class as the activity, and use context.sendBroadcast(msg of custom filter) and in the custom filter call updateUI (same as one but more generic?)

The final flow is it would come from a BroadcastReceiver and ends up updating the UI without renewing the activity (unless the activity is dead?)

Kindly provide links/source code on your how you tackle this kind of problem. Thanks a lot in advance :)

+1  A: 

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.

jwriteclub