Use EventBus to exit the APP with one key to close all activities

Previously used Application new List<Activity> to store each opened activity, and then traverse the finish. 

But if the operation is not good, there will be a memory overflow, because the list still holds the activity when the activity is finished by your code. 

Of course you can remove him before finishing, but it is too much trouble.

EventBus is recommended here 

 Home Register

EventBus.getDefault().register(this);

Then send the notification where you need it

@Override 
public void onBackPressed() { 
//Send close notification, all activities registered by you will receive notification 
    sendMessage(EXIT_APP, ""); 
}
/* 
 *Notification 
 */ 
protected void acceptMessage(int code, Object object) { 
  //Receive the closing page 
   if(code==EXIT_APP){ 
       if(!isFinishing()){ 
          finish(); 
       } 
   } 
}
The following is the outer method 

// send message 
public void sendMessage(int code, Object o) { 
    if (eventBean == null) { 
        eventBean = new EventBean(); 
    } 
    eventBean.setCode(code); 
    eventBean.setJob(o); 
    EventBus.getDefault().postSticky(eventBean); 
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void simpleEventBus(EventBean userEvent) {
    acceptMessage(userEvent.getCode(), userEvent.getJob());
}

Remember to unbind

@Override
protected void onDestroy() {
    super.onDestroy();
    EventBus.getDefault().removeAllStickyEvents();
    EventBus.getDefault().unregister(this);
}

Guess you like

Origin blog.csdn.net/qq_36767261/article/details/108801548