RxBus告訴你:Android應用如何完全退出“最優雅”
首先,在基類BaseActivity里,注冊RxBus監聽:
public class BaseActivity extends AppCompatActivity {
Subscription mSubscription;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Utils.intiSySBar(this, R.color.colorblack);
initRxBus();
}
//接收退出的指令,關閉所有activity
private void initRxBus() {
mSubscription = RxBus.getInstance().toObserverable(NormalEvent.class)
.subscribe(new Action1<NormalEvent>() {
@Override
public void call(NormalEvent userEvent) {
if (userEvent.getType() == -1) {
finish();
}
}
},
new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (!mSubscription.isUnsubscribed()) {
mSubscription.unsubscribe();
}
}
}
這是事件實體NormalEvent:
public class NormalEvent {
private int type;
public NormalEvent(int type) {
this.type = type;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
最后,在需要退出的地方調用:
RxBus.getInstance().post(new NormalEvent(-1));//發送退出指令
大功告成!