Android Jetpack架构组件之Lifecycle

LifeCycle

https://developer.android.google.cn/topic/libraries/architecture/lifecycle

LifeCycle应用

使用ltifecycle解耦页面与组件
使用LifecycleService解耦Service与组件
使用ProcessLifecycleOwner监听应用程序生命周期

LifeCycle的好处

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

控件结合Lifecycle
public class MyChronometer extends Chronometer implements Lifecycle0bserver {
	private long elapsedTime;
    
	public MyChronometer (Context context, AttributeSet attrs) {
		super ( context, attrs) ;
	}
    
    @OnLifecycleEvent (Lifecycle.Event.ONRESUME)   
	private void startMeter ( ) {
		setpase (SystemClock.elapsedRealtime() - elapsedTime) ;
        start ( );
	}
    
    @OnLifecycleEvent (Lifecycle.Event.ONSTOP)    
	private void stopMeter ( ) {
		elapsedTime = SystemClock.elapsedRealtime() - getBase();
        stop () ;
    }
}

//Activity添加监听
getLifecycle().addOnserver(chronomter)
 
//service
public class MyLocationService extends LifecycleService {
    public MyLocationService ( ) {
		Log.d ( tag: "ning" , msg: "MyLocationService" ) ;
		MyLocation0bserver observer = new MyLocationObserver ( context: this) ;
        getLifecycle ( ) .addobserver (observer) ;
    }
}

你可能感兴趣的:(Jetpack,android,jetpack,lifecycle)