帶觀察者模式的BaseActivity

老樣子,直接貼代碼!!!

需要導入Retrofit+Rxjava和ButterKnife。至於一些工具類之前在博客中寫過,拷貝即可。

首先是BaseActivity:

public abstract class BaseActivity<P extends BasePresenter> extends AppCompatActivity {

    public App application;

    public Handler mHandler;

    public Toast toast;

    protected P mPresenter;
    private Thread.UncaughtExceptionHandler sUncaughtExceptionHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //初始化佈局,並且適配
        View view = View.inflate(this, getLayout(), null);
        AutoUtils.setSize(this, false, 720, 1280);
        AutoUtils.auto(view);
        setContentView(view);
        //禁止橫屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        //禁止鍵盤擠壓佈局
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        ButterKnife.bind(this);
        mHandler = new myhandle(this);
        application = App.getApp();
        toast = new Toast(this);
        if (onCreatePresenter() != null) {
            mPresenter = onCreatePresenter();
        }
        App.getApp().addActivity(this);
        initData();

        //上線前解開
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                //主線程異常攔截
                while (true) {
                    try {
                        Looper.loop();//主線程的異常會從這裏拋出
                    } catch (Throwable e) {
                    }
                }
            }
        });
        sUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
        //所有線程異常攔截,由於主線程的異常都被我們catch住了,所以下面的代碼攔截到的都是子線程的異常
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {

            }
        });
    }

    //加載佈局
    public abstract int getLayout();

    //加載數據
    public abstract void initData();


    public static class myhandle extends Handler {
        //使用弱引用防止內存泄漏
        WeakReference<BaseActivity> activityWeakReference;

        public myhandle(BaseActivity activityWeakReference) {
            this.activityWeakReference = new WeakReference<BaseActivity>(activityWeakReference);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (activityWeakReference.get() != null) {
                activityWeakReference.get().handlerMeaasg(msg);
            }
        }
    }

    public static int MIN_DELAY_TIME = 1000;  // 兩次點擊間隔不能少於1000ms
    private static long lastClickTime;

    public static boolean isFastClick() {
        boolean flag = true;
        long currentClickTime = System.currentTimeMillis();
        if ((currentClickTime - lastClickTime) >= MIN_DELAY_TIME) {
            flag = false;
        }
        lastClickTime = currentClickTime;
        return flag;
    }

    //子類可以同時重寫這個方法實現Handler傳輸
    public void handlerMeaasg(Message msg) {
    }

    // 內存緊張時回收圖片資源
    @Override
    public void onLowMemory() {
        super.onLowMemory();
        Glide.get(this).clearMemory();
    }

    // 內存緊張時回收圖片資源 API4.0
    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        Glide.get(this).trimMemory(level);
    }

    //Acitiy銷燬時反註冊插件,並且移除活動
    @Override
    protected void onDestroy() {
        application.removeActivity(this);
        ButterKnife.unbind(this);
        if (mPresenter != null) {
            mPresenter.unSubscribe();
        }
        super.onDestroy();
    }

    public void showToast(String msg) {
        if (toast != null) {
            toast.cancel();
        }
        toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    private ProgressDialog dialog;

    public void showLoading() {
        if (dialog != null && dialog.isShowing()) {
            return;
        }
        dialog = new ProgressDialog(this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setMessage(getString(R.string.loading));
        dialog.show();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (msg.what == 10) {
                dismissLoading();
            }


        }
    };

    public void dismissLoading() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    //輸入框下劃線效果
    public void lineSelector(EditText[] etArray, final TextView[] tvArray) {
        for (int i = 0; i < etArray.length; i++) {
            final int position = i;
            etArray[i].setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    if (hasFocus) {
                        //此處爲得到焦點時
                        tvArray[position].setEnabled(true);
                    } else {
                        //此處爲失去焦點時
                        tvArray[position].setEnabled(false);
                    }
                }
            });
        }
    }

    protected abstract P onCreatePresenter();

    /**
     * 清楚webview 緩存
     *
     * @param wv webview
     */
    public static void WebViewClearUtils(WebView wv) {
        wv.setWebChromeClient(null);
        wv.setWebViewClient(null);
        wv.getSettings().setJavaScriptEnabled(false);
        wv.clearCache(true);
    }
}

 

可以發現BasePresenter還沒有:

public class BasePresenter<V extends BaseView, M extends BaseModel> {

    protected V mView;
    protected M mModel;

    private CompositeSubscription mCompositeSubscription;

    /**
     * 添加訂閱者
     *
     * @param subscription
     */
    protected void addSubscribe(Subscription subscription) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(subscription);
    }

    /**
     * 移除訂閱者,防止內存泄漏
     */
    protected void unSubscribe() {
        if (mView != null) {
            mView = null;
        }
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.clear();
        }
    }

}

還少兩個BaseView和BaseModel:

public interface BaseView {
}
public interface BaseModel {
}

完事了,拷貝即可使用,下一篇寫一下使用Mvp加Retrofit+Rxjava實現的網絡請求
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章