MainActivity.java两个启动停止service按钮
public class MainActivity extends AppCompatActivity { private static final String TAG = "Location"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void start(View view) { Intent intent = new Intent(MainActivity.this,MyService.class); startService(intent); } public void stop(View view) { Intent intent = new Intent(MainActivity.this,MyService.class); stopService(intent); } }运行结果
MyService是被观察者,MyServiceObserver是观察者,当被观察者MyService的生命周期发生变化时,回调观察者MyServiceObserver的指定方法
// startservice
MyServiceObserver: onCreate
MyServiceObserver: 在MyServiceObserver中监听到Service启动
// stopservice
MyServiceObserver: 在MyServiceObserver中监听到Service停止
MyServiceObserver: onDestroy
监听app的生命周期需要添加依赖,和监听service的依赖相同
implementation \'androidx.lifecycle:lifecycle-extensions:2.2.0\'
MyApp.java
ProcessLifecycleOwner
public class MyApp extends Application { @Override public void onCreate() { super.onCreate(); ProcessLifecycleOwner.get().getLifecycle().addObserver(new ApplicatonOberver()); } }ApplicatonOberver.java
package com.xinhe.testandroid; import android.util.Log; import androidx.lifecycle.Lifecycle; import androidx.lifecycle.LifecycleObserver; import androidx.lifecycle.OnLifecycleEvent; class ApplicatonOberver implements LifecycleObserver { private static final String TAG = "ApplicatonOberver"; @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) public void onCreate(){ Log.d(TAG,"onCreate in ApplicatonOberver"); } @OnLifecycleEvent(Lifecycle.Event.ON_START) public void onStart(){ Log.d(TAG,"onStart in ApplicatonOberver"); } @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) public void onResume(){ Log.d(TAG,"onResume in ApplicatonOberver"); } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) public void onPause(){ Log.d(TAG,"onPause in ApplicatonOberver"); } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) public void onStop(){ Log.d(TAG,"onStop in ApplicatonOberver"); } /** * 该方法永远不会被调用,因为系统不会分发ON_DESTROY事件 */ @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) public void onDestroy(){ Log.d(TAG,"onDestroy in ApplicatonOberver"); } }运行结果
APP刚启动时会依次执行以下三种方法
onCreate in ApplicatonOberver
onStart in ApplicatonOberver
onResume in ApplicatonOberver
APP切换到后台时会执行以下两种方法
onPause in ApplicatonOberver
onStop in ApplicatonOberver
APP再次切换到前台时会执行以下两种方法
onStart in ApplicatonOberver
onResume in ApplicatonOberver
APP退出
onPause in ApplicatonOberver
onStop in ApplicatonOberver
过ProcessLifecycleOwner我们可以轻易地检测到APP合适从前台进入到后台,又是何时从后台进入前台,进而可以进行一些业务操作,并且不会增加耦合度
ProcessLifecycleOwner是针对整个应用程序的监听,与Activity无关。
Lifecycle.Event.ON_CREATE只会调用一次,Lifecycle.Event.ON_DESTROY永远不会被调用。
Lifecycle.Event.ON_START 和 Lifecycle.Event.ON_RESUME是一组,会依次调用,Lifecycle.Event.ON_START在Lifecycle.Event.ON_RESUME之前调用。
Lifecycle.Event.ON_PAUSE 和 Lifecycle.Event.ON_STOP是一组,会依次调用,而且Lifecycle.Event.ON_PAUSE在Lifecycle.Event.ON_STOP之前调用。