前言:
各位同學(xué)大家好脉执,相信各位同學(xué)在開發(fā)安卓的時(shí)候都有用過四大組件之一的service吧 今天我們就通過一個(gè)獲取gps 定位的小案例來講一下用 LifeCycle解耦service 組件
需要用到的三方庫
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
具體實(shí)現(xiàn):
創(chuàng)建我們的 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) {
}
}
}
我們?cè)?MylocationObserver 定義了 startGetlocation 方法和 stopGetlocation 方法分別來出來獲取gps位置信息開始和結(jié)束 然后在方法上面分別加上 @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) 和
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) 注解 這樣我們就將原來要寫在service 內(nèi)部的邏輯 抽離到我們的 MylocationObserver 里面了 剩下就是獲取 gps 信息的一些代碼實(shí)現(xiàn)
@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);
}
然后我們?cè)?LocationListener 的實(shí)現(xiàn)方法 onLocationChanged 內(nèi)部打印 位置信息
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) {
}
}
創(chuàng)建我們的service 繼承 LifecycleService 然后通過調(diào)用 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);
}
}
我們?cè)赼ctivity 里面去啟動(dòng)的我們的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="啟動(dòng)"
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>
我們?cè)?個(gè)button點(diǎn)擊事件里面去啟動(dòng)和暫停我們的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));
}
}
我們現(xiàn)在來觀察日志
改變之前的位置信息
改變之后位置信息
最后總結(jié)
同學(xué)們發(fā)現(xiàn)了沒有 原來傳統(tǒng)的我們要在service 和activity 操作的大量的邏輯代碼 我們都可以用lifecycle 來解耦 使得我們的service 代碼更加簡(jiǎn)潔明了 耦合性也更低 不會(huì)在需求變動(dòng)的時(shí)候?qū)е乱惶幐膭?dòng)到處出問題的尷尬情況先匪。有興趣的同學(xué)可以自己再多研究蕴坪。這里就不展開深入講了篇幅有限镇匀。最后希望我的文章能幫助到各位解決問題 干奢,以后我還會(huì)貢獻(xiàn)更多有用的代碼分享給大家快耿。各位同學(xué)如果覺得文章還不錯(cuò) ,麻煩給關(guān)注和star纽乱,小弟在這里謝過啦!