先导入依赖
Kotlin
implementation("androidx.lifecycle:lifecycle-extensions:2.2.0")
1.使用LifeCycle解耦页面与组件
Activity
java
package com.tiger.lifecycle;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.SystemClock;
import android.widget.Chronometer;
import androidx.appcompat.app.AppCompatActivity;
public class Step2Activity 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);//给自定义组件添加 Activity生命周期的这个一个监听
}
}
自定义组件
java
package com.tiger.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 elapsedTime=0;
public MyChronometer(Context context, AttributeSet attrs) {
super(context, attrs);
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME) //在 resume 生命周期执行
private void startMeter(){
setBase(SystemClock.elapsedRealtime()-elapsedTime);
start();
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)//在 PAUSE 生命周期执行
private void stopMeter(){
elapsedTime = SystemClock.elapsedRealtime() - getBase();
stop();
}
}
xml
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=".Step1Activity">
<com.tiger.lifecycle.MyChronometer
android:id="@+id/chronometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">
</com.tiger.lifecycle.MyChronometer>
</androidx.constraintlayout.widget.ConstraintLayout>
2.使用LifeCycle解耦Service与组件
activity
java
package com.tiger.lifecycle;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
public class Step3Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_two);
}
public void startGps(View view) {
startService(new Intent(this,MyLocationService.class));
}
public void stopGps(View view) {
stopService(new Intent(this,MyLocationService.class));
}
}
service
java
package com.tiger.lifecycle;
import android.util.Log;
import androidx.lifecycle.LifecycleService;
public class MyLocationService extends LifecycleService {
public MyLocationService() {
Log.d("ning","MyLocationService init");
MyLocationObserver myLocationObserver = new MyLocationObserver(this);
getLifecycle().addObserver(myLocationObserver);
}
}
observer
java
package com.tiger.lifecycle;
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.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;
import java.util.List;
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)
private void startGetLocation() {
Log.d("ning","startGetLocation");
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
myLocationListener = new MyLocationListener();
if (ActivityCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//不满足就退出方法
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 1, myLocationListener);//提供监听 GPS提供 ,每3秒获取一下信息,每拿手机移动一米获取一下信息
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
private void stopGetLocation(){
Log.d("ning","stopGetLocation");
locationManager.removeUpdates(myLocationListener);
}
static class MyLocationListener implements LocationListener{
@Override
public void onLocationChanged(@NonNull Location location) {
Log.d("ning","Location Changed "+location.toString());
}
@Override
public void onLocationChanged(@NonNull List<Location> locations) {
LocationListener.super.onLocationChanged(locations);
}
@Override
public void onFlushComplete(int requestCode) {
LocationListener.super.onFlushComplete(requestCode);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
LocationListener.super.onStatusChanged(provider, status, extras);
}
@Override
public void onProviderEnabled(@NonNull String provider) {
LocationListener.super.onProviderEnabled(provider);
}
@Override
public void onProviderDisabled(@NonNull String provider) {
LocationListener.super.onProviderDisabled(provider);
}
}
}
3.使用ProcessLifecycleOwner监听应用程序生命周期
java
package com.tiger.lifecycle;
import android.util.Log;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;
public class ApplicationObserver implements LifecycleObserver {
private String TAG = "ning";
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreate() {
Log.d(TAG, "Lifecycle.Event.ON_CREATE");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart() {
Log.d(TAG, "Lifecycle.Event.ON_START");
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume() {
Log.d(TAG, "Lifecycle.Event.ON_RESUME");
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause() {
Log.d(TAG, "Lifecycle.Event.ON_PAUSE");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStop() {
Log.d(TAG, "Lifecycle.Event.ON_STOP");
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy() {
Log.d(TAG, "Lifecycle.Event.ON_DESTROY");
}
}
MyApplication
java
package com.tiger.lifecycle;
import android.app.Application;
import android.util.Log;
import androidx.lifecycle.ProcessLifecycleOwner;
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
ProcessLifecycleOwner.get().getLifecycle().addObserver(new ApplicationObserver());//只有一个会执行,多个Activity只执行一次
Log.d("ning","MyApplication onCreate");
}
}