前言:
各位同学大家好,相信各位同学在开发安卓的时候都有用过四大组件之一的service吧 今天我们就通过一个获取gps 定位的小案例来讲一下用 LifeCycle解耦service 组件
需要用到的三方库
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
具体实现:
创建我们的 MylocationObserver 继承 LifecycleObserver
package com.example.lifecycleservice;
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.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 static final String TAG = "MylocationObserver";
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.e(TAG, "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, (LocationListener) locationManager);
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void stopGetlocation(){
Log.e(TAG, "stopGetlocation: " );
locationManager.removeUpdates(mylocationListener);
}
static class MylocationListener implements LocationListener {
@Override
public void onLocationChanged(@NonNull Location location) {
Log.e(TAG, "onLocationChanged: " +location.toString());
}
@Override
public void onLocationChanged(@NonNull List<Location> locations) {
}
@Override
public void onFlushComplete(int requestCode) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(@NonNull String provider) {
}
@Override
public void onProviderDisabled(@NonNull String provider) {
}
}
}
我们在 MylocationObserver 定义了 startGetlocation 方法和 stopGetlocation 方法分别来出来获取gps位置信息开始和结束 然后在方法上面分别加上 @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) 和
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) 注解 这样我们就将原来要写在service 内部的逻辑 抽离到我们的 MylocationObserver 里面了 剩下就是获取 gps 信息的一些代码实现
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void startGetlocation() {
Log.e(TAG, "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, (LocationListener) locationManager);
}
然后我们在 LocationListener 的实现方法 onLocationChanged 内部打印 位置信息
static class MylocationListener implements LocationListener {
@Override
public void onLocationChanged(@NonNull Location location) {
Log.e(TAG, "onLocationChanged: " +location.toString());
}
@Override
public void onLocationChanged(@NonNull List<Location> locations) {
}
@Override
public void onFlushComplete(int requestCode) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(@NonNull String provider) {
}
@Override
public void onProviderDisabled(@NonNull String provider) {
}
}
创建我们的service 继承 LifecycleService 然后通过调用 getLifecycle().addObserver(mylocationObserver) 来绑定我们的MylocationObserver
package com.example.lifecycleservice;
import android.util.Log;
import androidx.lifecycle.LifecycleService;
public class MylocationService extends LifecycleService {
private static final String TAG = "MylocationService";
public MylocationService() {
Log.e(TAG, "MylocationService: " );
MylocationObserver mylocationObserver=new MylocationObserver(this);
getLifecycle().addObserver(mylocationObserver);
}
}
我们在activity 里面去启动的我们的service
<?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="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="151dp"
android:layout_marginTop="156dp"
android:layout_marginEnd="172dp"
android:layout_marginBottom="137dp"
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"
tools:ignore="OnClick" />
<Button
android:id="@+id/button2"
android:layout_width="88dp"
android:layout_height="wrap_content"
android:layout_marginStart="151dp"
android:layout_marginTop="137dp"
android:layout_marginEnd="172dp"
android:layout_marginBottom="342dp"
android:onClick="stopGPS"
android:text="暂停"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button"
tools:ignore="OnClick" />
</androidx.constraintlayout.widget.ConstraintLayout>
我们在2个button点击事件里面去启动和暂停我们的service
package com.example.lifecycleservice;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startGps(View view){
Log.e(TAG, "startGps: "+"开始" );
startService(new Intent(this,MylocationService.class));
}
public void stopGPS(View view){
Log.e(TAG, "stopGPS: "+"暂停" );
stopService(new Intent(this,MylocationService.class));
}
}
我们现在来观察日志
改变之前的位置信息
改变之后位置信息
最后总结
同学们发现了没有 原来传统的我们要在service 和activity 操作的大量的逻辑代码 我们都可以用lifecycle 来解耦 使得我们的service 代码更加简洁明了 耦合性也更低 不会在需求变动的时候导致一处改动到处出问题的尴尬情况。有兴趣的同学可以自己再多研究。这里就不展开深入讲了篇幅有限。最后希望我的文章能帮助到各位解决问题 ,以后我还会贡献更多有用的代码分享给大家。各位同学如果觉得文章还不错 ,麻烦给关注和star,小弟在这里谢过啦!