RxBus告訴你:Android應用如何完全退出“最優雅”

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));//發送退出指令

大功告成!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容