Thursday, April 7, 2011

Android: Broadcast Receivers made simple

Lets say you have a requirement:
App starts with Activities A,B and C and then Activity D is started.
A,B and C are the activities for just one time like Terms and Conditions etc, that user should not be able to see them once he has successfully navigated from A->B->C and then to D.

Lets solve this basic problem using BroadcastReceivers:

In your Activity A:

Activity A{

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

...
IntentFilter myFilter = new IntentFilter("finish"); // "finish" can be any string you wanna provide
registerReceiver(myReceiver, myFilter);


}


BroadcastReceiver myReceiver = new BroadcastReceiver() {

@Override
public void onReceive(Context context, Intent intent) {
Log.d("ActivityA", "finishing A");
finish();
}
};

@Override
protected void onDestroy() {
unregisterReceiver(myReceiver);
super.onDestroy();
}


}

Similarly register for this broadcast receiver in all other activities you wanna finish at a single action.

Now in Activity D,

you just need to call
sendBroadcast(new Intent("finish"));


at the point where you want that all the activities who have registered for your receiver must get finished.

P.S. Its mandatory to unregister the receiver at some point else there can be a possible exception.

No comments:

Post a Comment