LifeCycle-02-解耦service与组件------
我们知道,拥有生命周期概念的组件,除了Activity和Fragment,还有一个非常重要的组件是Service。
为了方便我们对Service生命周期的监听,Android提供了一个名为LifecycleService的类,该类继承自Service,并实现LifecycleOwner接口。
由于LifecycleService存在于扩展包中,所以,首先我们需要在app的build.gradle文件中添加依赖:
implementation 'android.arch.lifecycle:extensions:1.1.1'
该例子有四个文件
MyObserver.class
//获取位置信息的一种监听 public class MyObserver implements LifecycleObserver { Context context; //把service传进来 public MyObserver(Context context) { this.context = context; } @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) private void startGetLocation() { Toast.makeText(context.getApplicationContext(), "服务开启", Toast.LENGTH_SHORT).show(); } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) private void stopGetLocation(){ Toast.makeText(context.getApplicationContext(), "服务关闭", Toast.LENGTH_SHORT).show(); } }
MyService.class
//别忘了去清单中注册service奥 application中 /* ** */ public class MyService extends LifecycleService{ public MyService() { Log.e("ning",getClass().getName()); MyObserver myObserver = new MyObserver(this); getLifecycle().addObserver(myObserver); } }
MainActivity.class
//lifecycle就是监听activity或者fragment的生命周期的 public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void startGps(View view){ startService(new Intent(this,MyService.class)); } public void stopGps(View view){ stopService(new Intent(this,MyService.class)); } }
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"> <Button android:id="@+id/button" android:layout_width="141dp" android:layout_height="59dp" android:layout_marginTop="196dp" android:layout_marginBottom="145dp" android:text="开始" android:onClick="startGps" 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="137dp" android:layout_height="59dp" android:layout_marginBottom="272dp" android:text="结束" android:onClick="stopGps" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.492" app:layout_constraintStart_toStartOf="parent" /> androidx.constraintlayout.widget.ConstraintLayout>