android LifeCycle解耦service 組件

前言:
各位同學(xué)大家好,相信各位同學(xué)在開(kāi)發(fā)安卓的時(shí)候都有用過(guò)四大組件之一的service吧 今天我們就通過(guò)一個(gè)獲取gps 定位的小案例來(lái)講一下用 LifeCycle解耦service 組件

需要用到的三方庫(kù)

   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 方法分別來(lái)出來(lái)獲取gps位置信息開(kāi)始和結(jié)束 然后在方法上面分別加上 @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) 和
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) 注解 這樣我們就將原來(lái)要寫(xiě)在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 然后通過(guò)調(diào)用 getLifecycle().addObserver(mylocationObserver) 來(lái)綁定我們的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>
image.png

我們?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: "+"開(kāi)始" );
        startService(new Intent(this,MylocationService.class));
    }
    public  void stopGPS(View view){
        Log.e(TAG, "stopGPS: "+"暫停" );
        stopService(new Intent(this,MylocationService.class));
    }
}

我們現(xiàn)在來(lái)觀察日志

改變之前的位置信息

image.png

改變之后位置信息
image.png

最后總結(jié)

同學(xué)們發(fā)現(xiàn)了沒(méi)有 原來(lái)傳統(tǒng)的我們要在service 和activity 操作的大量的邏輯代碼 我們都可以用lifecycle 來(lái)解耦 使得我們的service 代碼更加簡(jiǎn)潔明了 耦合性也更低 不會(huì)在需求變動(dòng)的時(shí)候?qū)е乱惶幐膭?dòng)到處出問(wèn)題的尷尬情況。有興趣的同學(xué)可以自己再多研究。這里就不展開(kāi)深入講了篇幅有限。最后希望我的文章能幫助到各位解決問(wèn)題 ,以后我還會(huì)貢獻(xiàn)更多有用的代碼分享給大家。各位同學(xué)如果覺(jué)得文章還不錯(cuò) ,麻煩給關(guān)注和star,小弟在這里謝過(guò)啦!

項(xiàng)目地址

碼云 :https://gitee.com/qiuyu123/lifecycleservice

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容