Android jetpack(Lifecycle篇)

今天逛,看到有人问Android 怎么监听整个应用进入了后台,我看底下的评论有人说,做一个BaseActivity,进入一个Activity就往集合里面加入,当加入的所有activity都进入onPause阶段了就是进入后台模式了。
确实如此,但是好累啊。谷歌早就为我们想到了这一点,jetpack的Lifecycle就能很方便的解决。
选Lifecycle中重要的三个使用案例,做一份笔记

Lifecycle绑定自定义view解耦

Chronometer是Android提供的计时控件,提供了start和stop以及setBase等基本方法。

    private Chronometer myChronometer;
    private long elapsedTime;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_life_cycle);
        myChronometer = findViewById(R.id.chronometer);
    }

    @Override
    protected void onResume() {
        super.onResume();
        myChronometer.setBase(SystemClock.elapsedRealtime() - elapsedTime);
        myChronometer.start();
    }

    @Override
    protected void onPause() {
        super.onPause();
        elapsedTime = SystemClock.elapsedRealtime() - myChronometer.getBase();
        myChronometer.stop();
    }

这样,我们就能实现在页面进入onPause时停止计时的功能,返回也从上一次退出时的时间开始计时。
但是这样的话我们就在activity里面写了view的逻辑控制代码。我们最好是把这个绑定生命周期的代码写进view中,那么我们就自定义一个MyChronometer来实现

public class MyChronometer extends Chronometer implements LifecycleObserver {

    private long elapsedTime;

    public MyChronometer(Context context) {
        this(context,null);
    }

    public MyChronometer(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public MyChronometer(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    private void startImp(){
        setBase(SystemClock.elapsedRealtime() - elapsedTime);
        start();
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    private void stopImp(){
        elapsedTime = SystemClock.elapsedRealtime() - getBase();
        stop();
    }
}

@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)就代表我们监听activity的onResume方法。调用时需要将监听加入。在activity中

getLifecycle().addObserver(myChronometer);

利用LifecycleService绑定service实现解耦

public class WifiService extends LifecycleService implements LifecycleObserver {
    public static final int TYPE_WIFI = 1;
    public static final int TYPE_MOBILE = 2;
    public static final int TYPE_NOT_CONNECTED = 0;
    public WifiService() {
        getLifecycle().addObserver(this);
    }

    /**
     * 开启监听网络状态
     */
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    private void startWifi(){
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (null != activeNetwork) {
            if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
                Log.d("yanjin","当前网络状态为wifi");

            if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
                Log.d("yanjin","当前网络状态为移动网络");
        }else{
            Log.d("yanjin","当前没有网络");
        }

    }

    /**
     * 停止监听网络状态
     */
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    private void stopWifi(){
        Log.d("yanjin","停止监听");
    }
}

然后在activity中开启和关闭service,看看有没有log。

        findViewById(R.id.mButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startService(new Intent(LifeCycleActivity.this,WifiService.class));
            }
        });
        findViewById(R.id.mButton2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopService(new Intent(LifeCycleActivity.this,WifiService.class));
            }
        });

ProcessLifecycleOwner监听应用的生命周期

在Application的oncreate中加入监听

public class MyApp extends Application {
    private static MyApp instance;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        ProcessLifecycleOwner.get().getLifecycle().addObserver(new ApplicationLifecycle());
    }

    public static MyApp getInstance() {
        return instance;
    }
}
public class ApplicationLifecycle implements LifecycleObserver {
    public ApplicationLifecycle(){

    }
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void create(){
        Log.d("yanjin","create");
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void start(){
        Log.d("yanjin","start");
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void resume(){
        Log.d("yanjin","resume");
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void pause(){
        Log.d("yanjin","pause");
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void stop(){
        Log.d("yanjin","stop");
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void destroy(){
        Log.d("yanjin","destroy");
    }
}

destroy是没有打印的,唯一的遗憾点,create只打印了一次。利用这个我们就能控制好应用是否进入后台了

你可能感兴趣的:(Android jetpack(Lifecycle篇))