i have one activity Main.java is open in my application, i want to close the activity using broadcast receiver , how to close the activity?
Asked
Active
Viewed 1.0k times
3
-
i am asking about is there way to implement this? – appukrb Dec 20 '12 at 11:40
3 Answers
6
Firstly your Main.java needs to be registered as a receiver. You could register it in Main.java's onResume():
@Override
public void onResume() {
registerReceiver(broadcastReceiver, new IntentFilter(BroadcasterClassName.NAME_OF_ACTION));
}
Then handle the broadcast and finish your activity:
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(BroadcasterClassName.NAME_OF_ACTION)) {
finish();
}
}
}

jesobremonte
- 3,198
- 2
- 22
- 30
-
@Jack Sobremonte thanks for your answer, i accept your code but i have two java class file main.java is my activity and receiver.java is my broad cast receiver file then how i call the activity using the receiver class file... – appukrb Dec 20 '12 at 12:07
-
Then your Main.java would need to extend Receiver, and Receiver.java will extend Activity – jesobremonte Dec 20 '12 at 12:12
-
I ended up using a LocalBroadcastReceiver to get mine working. Check out the post that helped me [here](http://stackoverflow.com/questions/8802157/how-to-use-localbroadcastmanager) – oddmeter Apr 11 '14 at 12:41
0
You could send a message to the activity which implements Handler.Callback, and handle it there to close the activity.
Quick example:
class Act1 extends Activity implements Handler.Callback {
public static final int CLOSE_ACTIVITY = 54212;
public boolean handleMessage(Message msg) {
if(msg.what == CLOSE_ACTIVITY) {
finish();
}
}
}
And then, since you BroadcastReceiver runs on main thread, in most of the cases. Just send the message via Handler.
new Handler().sendMessage(MessageFactory.createShutdownMsg()).

nullpotent
- 9,162
- 1
- 31
- 42
-1
you could do this: in your main have:
private static Main mInstance;
onCreate()
{
...
mInstance = this;
}
public static boolean closeActivity()
{
if (mInstance != null)
{
mInstance.finish();
return true;
}
return false;
}
although, this implies only one Main exists at any one time. I think you can achieve that by adding android:noHistory="true" or something similar in the manifest.

twigg
- 146
- 6