问题
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?
回答1:
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();
}
}
}
回答2:
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()).
回答3:
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.
来源:https://stackoverflow.com/questions/13971348/close-activity-using-broadcastreceiver