Android组件Lifecycle配合java8接口写监听

Google官方在 I/O大会中引入一些列Android新的体系架构内容,其中有一个是Android的Lifecycle。他的一些便利之处。

AS中添加依赖

首先在工程根目录的build.gradle中添加一下内容:

allprojects {
    repositories {
        jcenter()
        maven { url 'https://maven.google.com' }  //添加此行
    }
}

然后在应用目录下的build.gradle中添加以下依赖:

implementation "android.arch.lifecycle:extensions:1.1.1"
annotationProcessor "android.arch.lifecycle:compiler:1.1.1"

项目中我们经常会使用一些监听,比如网络监听

原先我们大概是这么写的:

/**
  回调接口
*/
public interface NetworkListener  {
    /**
     * @param isNetConnect 是否连接网络
     */
    void networkChange(boolean isNetConnect);
}

网络监听的管理类:

//Observable是android.database;包下的,提供注册监听和反注册等几个方法
//7.0以后还是可以用动态广播监听网络状态的,这里就不讲这些适配问题了
public class NetworkManager extends Observable {

    private boolean isNetConnect = true;
    private NetworkChangedBroadcastReceiver mNetworkChangedBroadcastReceiver;

    private NetworkManager() {
        registerNetworkChangedBroadcastReceiver();
    }

    public boolean isNetConnect() {
        return isNetConnect;
    }

    private static class SingletonHolder {
        private static final NetworkManager INSTANCE = new NetworkManager();
    }

    //获取单例
    public static NetworkManager getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public void notifyChange(boolean isNetConnect) {
        this.isNetConnect = isNetConnect;
        for (NetworkListener mObserver : mObservers) {
            if (mObserver != null) mObserver.networkChange(isNetConnect);
        }
    }

    private void registerNetworkChangedBroadcastReceiver() {
        try {
            mNetworkChangedBroadcastReceiver = new NetworkChangedBroadcastReceiver();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            BaseApplication.getApplication().registerReceiver(mNetworkChangedBroadcastReceiver, intentFilter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //在Application的onTerminate方法进行反注册
    public void unregisterNetworkChangedBroadcastReceiver() {
        try {
            if (mNetworkChangedBroadcastReceiver != null)
                BaseApplication.getApplication().unregisterReceiver(mNetworkChangedBroadcastReceiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class NetworkChangedBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction() != null && intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
                if (info != null) {
                    //如果当前的网络连接成功
                    notifyChange(info.isConnected());
                }
            }

        }
    }
}

activity中使用

public class MainActivity extends AppCompatActivity implements NetworkListener {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        NetworkManager.getInstance().registerObserver(this);
    }

    @Override
    public void networkChange(boolean isNetConnect) {
        Log.d("MainActivity", "isNetConnect:" + isNetConnect);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        NetworkManager.getInstance().unregisterObserver(this);
    }
}

NetworkManager.getInstance().registerObserver(this); NetworkManager.getInstance().unregisterObserver(this);
这两段代码监听多了写的很烦,又不是很好抽取,不是每个界面都需这些监听,特别反注册忘写就麻烦了,那么怎么办才能简化掉?

可以使用Lifecycle加Java8,java8可以允许接口里面有默认方法以及静态方法,不只是单纯的抽象方法,可以有方法体,接下来直接上代码。

NetworkManager不做任何改动,首先接口改造,抽取一个BaseListener,为了让其他类似的监听接口减少代码:

//LifecycleObserver继承它
public interface BaseListener extends LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    default void on_Create() {//java8写法,子类可以选择重写不会强制你去实现这个方法
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    default void on_Destroy() {
    }
}

@OnLifecycleEvent(Lifecycle.Event.ON_CREATE) @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
这里个注解很重要,它可以让接口感知activity的生命周期,除onCreate和onDestroy事件之外,Lifecycle一共提供了所有的生命周期事件,只要通过注解进行声明,就能够使LifecycleObserver观察到对应的生命周期事件,接下来网络监听接口:

public interface NetworkListener extends BaseListener {

    /**
     * @param isNetConnect 是否连接网络
     */
    void networkChange(boolean isNetConnect);

    @Override
    default void on_Create() {//重写,这边注册监听
        Log.d("log==", "注册啦");
        NetworkManager.getInstance().registerObserver(this);
    }

    @Override
    default void on_Destroy() {//反注册监听
        Log.d("log==", "取消注册");
        NetworkManager.getInstance().unregisterObserver(this);
    }
}

接下来就是简单了activity中只需要继承NetworkListener接口实现networkChange方法即可

public class MainActivity extends BaseActivity implements NetworkListener {

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_main;
    }

    @Override
    public void networkChange(boolean isNetConnect) {
        Log.d("log==", "isNetConnect:" + isNetConnect);
    }

}

运行效果:

D/log==: 注册啦
D/log==: isNetConnect:true
D/log==: 取消注册  //结束mainactivity

忘了另外一步了,最主要的BaseActivitygetLifecycle().addObserver(this);调用了这个方法就可以让实现LifecycleObserver的类可以感知生命周期

public abstract class BaseActivity extends AppCompatActivity implements View.OnClickListener {

    protected T mDataBind;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (this instanceof LifecycleObserver) getLifecycle().addObserver((LifecycleObserver) this);
        ActivityManager.getActivityManager().addActivity(this);
        int resID = getLayoutResID();
        if (resID != -1 && resID != 0) {
            mDataBind = DataBindingUtil.setContentView(this, resID);
        }

        initToolbar();
        initView();
        setListener();
        getData();
    }

    /**
     * 获取布局ID
     */
    protected abstract int getLayoutResID();

    /**
     * 初始化Toolbar
     */
    protected void initToolbar() {

    }

    /**
     * 初始化view
     */
    protected abstract void initView();

    /**
     * 设置监听
     */
    protected abstract void setListener();

    /**
     * 获取网络数据,获取数据后也在这里更新数据
     */
    protected abstract void getData();

    @Override
    public void onClick(View v) {

    }

    @Override
    public Resources getResources() {
        Resources resources = super.getResources();
        if (resources != null && resources.getConfiguration().fontScale != 1.0f) {
            android.content.res.Configuration configuration = resources.getConfiguration();
            configuration.fontScale = 1.0f;
            resources.updateConfiguration(configuration, resources.getDisplayMetrics());
        }
        return resources;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityManager.getActivityManager().removeActivity(this);
        if (mDataBind != null) mDataBind.unbind();//加快回收~
    }

}

配合mvp模式也是绝佳,可以让p层感知生命周期
原理就不在这边累述了,附上lifecycle官方文档
这边还稍微用到了另外一个组件DataBinding有兴趣的可以学习下

你可能感兴趣的:(Android组件Lifecycle配合java8接口写监听)