Andriod --- JetPack :LifeCycle 的诞生

Andriod — JetPack :初识 JetPack

Andriod — JetPack :LifeCycle 的诞生

Andriod — JetPack :ViewModel 的诞生

Andriod — JetPack :BaseObservable 与 ObservableField 双向绑定

Andriod — JetPack :DataBinding + LiveData +ViewModel 简单实例

Andriod — JetPack :Room 增删改查

Andriod — JetPack :Room + ViewModel + LiveData 增删改查实例

Andriod — JetPack :LiveData setValue 和 postValue 的区别

一、使用的原因

解耦系统组件与普通组件
Andriod --- JetPack :LifeCycle 的诞生_第1张图片

二、代码实例:LifeCycle解耦Activity与组件

比如一个普通控件 Chronometer 的使用与 Activity 的生命周期关联的太强,即普通控件 Chronometer 的业务逻辑必须在 Activity 的生命周期中处理,这样的耦合度就太高,所以我们使用LifeCycle 来解决

我们先来看没有使用 LifeCycle 之前的代码:
MainActivity.java

package com.example.lifecycle;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.SystemClock;
import android.widget.Chronometer;

public class MainActivity extends AppCompatActivity {
    private Chronometer chronometer;
    private Long elapseTime = 0l;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        chronometer = findViewById(R.id.chronometer);
    }

    // 活跃状态
    @Override
    protected void onResume() {
        super.onResume();
        chronometer.setBase(SystemClock.elapsedRealtime() - elapseTime); // 返回启动后的毫秒数,包括睡眠时间。
        chronometer.start();
    }

    // 转到后台
    @Override
    protected void onPause() {
        super.onPause();
        elapseTime = SystemClock.elapsedRealtime() - chronometer.getBase();
        chronometer.stop();
    }
}


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.example.lifecycle.MyChronometer
        android:id="@+id/chronometer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="36sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

很明显,Chronometer 的使用与 Activity 的生命周期关联的太强
我们来看一下修改之后的代码:

MainActivity2 .java

package com.example.lifecycle;

import android.os.Bundle;
import android.os.SystemClock;
import android.widget.Chronometer;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity2 extends AppCompatActivity {

    private MyChronometer chronometer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        chronometer = findViewById(R.id.chronometer);
        getLifecycle().addObserver(chronometer);
    }
}

自定义 MyChronometer 类继承 Chronometer 实现 LifecycleObserver
MyChronometer .java

package com.example.lifecycle;

import android.content.Context;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.widget.Chronometer;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

public class MyChronometer extends Chronometer implements LifecycleObserver {
    private Long elapseTime = 0l;

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

    // 通过注解的方式拥有 Activity 生命周期所拥有的方法
    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void startMeter() {
        setBase(SystemClock.elapsedRealtime() - elapseTime); // 返回启动后的毫秒数,包括睡眠时间。
        start();
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void stopMeter() {
        elapseTime = SystemClock.elapsedRealtime() - getBase();
        stop();
    }
}

通过注解的方式拥有 Activity 生命周期所拥有的方法,这样就在很大的程度上解耦了

三、代码实例:LifeCycleService解耦Service与组件

代码测试的时候记得开启GPS权限

添加依赖:

  implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0-alpha02'

AndroidMainfest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.lifecycle">

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity3">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity2">

        </activity>

        <service android:name=".MyLocationService" />
    </application>

</manifest>

MainActivity3.java

package com.example.lifecycle;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity3 extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity3_main);
    }

    public void startGps(View view) {
        startService(new Intent(this, MyLocationService.class));
    }

    public void stopGps(View view) {
        stopService(new Intent(this, MyLocationService.class));
    }
}

activity3_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity3">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="开始"
        android:onClick="startGps"
        android:textSize="36sp"
        app:layout_constraintBottom_toTopOf="@+id/button2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="240dp"
        android:text="停止"
        android:onClick="stopGps"
        android:textSize="36sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.501"
        app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

MyLocationService.java

package com.example.lifecycle;

import android.util.Log;

import androidx.lifecycle.LifecycleService;

public class MyLocationService extends LifecycleService {

    public MyLocationService() {
        Log.d("liang", "MyLocationService");
        MyLocationObserver myLocationObserver = new MyLocationObserver(this);
        getLifecycle().addObserver(myLocationObserver);
    }
}

MyLocationObserver.java

package com.example.lifecycle;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;

import androidx.core.app.ActivityCompat;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;

public class MyLocationObserver implements LifecycleObserver {
    private Context context;
    private LocationManager locationManager;
    private MyLocationListener myLocationListener;
    public MyLocationObserver(Context context) {
        this.context = context;
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void startGetLocation() {
        Log.d("liang", "startGetLocation");
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        myLocationListener = new MyLocationListener();
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 1, myLocationListener);
    }


    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void stopGetLocation() {
        Log.d("liang", "stopGetLocation");
        locationManager.removeUpdates(myLocationListener);
    }

    static class MyLocationListener implements LocationListener {

        @Override
        public void onLocationChanged(Location location) {
            Log.d("liang", "location changed" + location.toString());
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    }
}

可以在 Terminal 终端中通过一下命令改变位置信息

adb -s emulator-5554 emu geo fix 121.4961236714487 31.244010934431345

四、LifeCycle的好处

1.帮助开发者建立可感知生命周期的组件
2.组件在其内部管理自己的生命周期,从而降低模块耦合度
3.降低内存泄漏发生的可能性
4.Activity、Fragment、Service、Application均有LifeCycle支持

学习内容来自动脑学院~

你可能感兴趣的:(Android,项目开发笔记,android,java,JetPack,LifeCycle的诞生)