Android   发布时间:2022-04-28  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了android – 使用Google Play服务和FusedLocationProviderClient的位置更新大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我想使用最新的融合位置提供商客户端在“后台服务”上获取位置更新.我不想使用所有正在使用的位置监听器和Google Api客户端.
我还需要使用谷歌播放服务提供的位置设置Api来检查位置设置是否禁用或启用“后台服务”.请帮助.

解决方法

如果我们需要使用fusion LOCATIOn api,那么我们需要使用Google Api客户端,对于后台服务,使用它不是问题,以下是我用于在后台获取位置更新的示例,但还有一件事是Google从6.0引入’DOZE’模式,所以当你的设备处于’DOZE’模式时,我无法给予保证更新,
import android.Manifest;
import android.app.service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.LOCATIOn.LOCATIOn;
import android.os.build;
import android.os.bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.Annotation.NonNull;
import android.support.Annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.LOCATIOn.LOCATIOnListener;
import com.google.android.gms.LOCATIOn.LOCATIOnrequest;
import com.google.android.gms.LOCATIOn.LOCATIOnservices;

/**
 * Created By Dhaval Solanki
 */

public class Connectionservice extends service implements GoogleApiClient.ConnectionCallBACks,GoogleApiClient.onConnectionFailedListener,LOCATIOnListener {
    String TAG = "Connectionservice";


    private GoogleApiClient mGoogleApiClient;
    private LOCATIOnrequest mLOCATIOnrequest;
    private LOCATIOn prevIoUsLOCATIOn;
    public static final long updatE_INTERVAL_IN_MILLISECONDS = 30000;
    public static final long FAStest_updatE_INTERVAL_IN_MILLISECONDS =
            updatE_INTERVAL_IN_MILLISECONDS / 2;


    private LOCATIOn mLastLOCATIOn;
    private Context context;

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(tag,"onBind");
        return null;
    }

    @Override
    public int onStartCommand(Intent intent,int flags,int startId) {
        context = getApplicationContext();
        Log.i(tag,"onStartCommand");
        if (checkPermsion(context)) {
            setupLOCATIOnservice(context);
        }
        return service.START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        ApplicationCLass.isserviceRunning = true;
    }

    @Override
    public Boolean onUnbind(Intent intent) {
        Log.i(tag,"onUnbind");
        ApplicationCLass.isserviceRunning = false;
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        ApplicationCLass.isserviceRunning = false;
        super.onDestroy();
    }

    private void setupLOCATIOnservice(Context context) {
        if (checkPlayservices()) {
            mGoogleApiClient = new GoogleApiClient.builder(context)
                    .addApi(LOCATIOnservices.API)
                    .addConnectionCallBACks(this)
                    .addOnConnectionFailedListener(this)
                    .build();
            createLOCATIOnrequest();
        }
    }

    protected void createLOCATIOnrequest() {
        mLOCATIOnrequest = new LOCATIOnrequest().create();
        mLOCATIOnrequest.seTinterval(updatE_INTERVAL_IN_MILLISECONDS);
        mLOCATIOnrequest.setFastesTinterval(FAStest_updatE_INTERVAL_IN_MILLISECONDS);
        mLOCATIOnrequest.setPriority(LOCATIOnrequest.PRIORITY_BALANCED_POWER_ACCURACY);
        mGoogleApiClient.connect();
    }

    public Boolean checkPermsion(Context context) {
        int MyVersion = Build.VERSION.SDK_INT;
        if (MyVersion > Build.VERSION_CODEs.LOLLIPOP_MR1) {
            if (ContextCompat.checkSelfPermission(context,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return false;
            } else if (ContextCompat.checkSelfPermission(context,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    private Boolean checkPlayservices() {
        GoogleApiAvailability googleAPI = GoogleApiAvailability.geTinstance();
        int result = googleAPI.isGooglePlayservicesAvailable(this);
        if (result != ConnectionResult.succesS) {
            return false;
        }
        return true;
    }


    private void startLOCATIOnupdates() {
        if (mGoogleApiClient.isConnected()) {
            if (ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            if (Prefs.getUserLat(context).trim().length() > 0 && Prefs.getUserLong(context).trim().length() > 0) {
            } else {
                mLastLOCATIOn = LOCATIOnservices.FusedLOCATIOnApi.getLastLOCATIOn(
                        mGoogleApiClient);
                if (mLastLOCATIOn != null) {
                    Prefs.setUserLat(context,String.valueOf(mLastLOCATIOn.getLatitude()));
                    Prefs.setUserLong(context,String.valueOf(mLastLOCATIOn.getLongitude()));
                }
            }
            LOCATIOnservices.FusedLOCATIOnApi.requestLOCATIOnupdates(
                    mGoogleApiClient,mLOCATIOnrequest,this);
        }
    }

    @Override
    public void onConnected(@Nullable Bundle bundlE) {
        Log.i(tag,"Connected to onConnected");
        startLOCATIOnupdates();
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i(tag,"Connected to onConnectionSuspended");
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.i(tag,"Connected to onConnectionFailed");
    }

    @Override
    public void onLOCATIOnChanged(LOCATIOn LOCATIOn) {
        try {
            Logger.print("onLOCATIOnChanged","latitued :" + LOCATIOn.getLatitude() + ",Longitude " + LOCATIOn.getLongitude());
        } catch (Exception E) {
            e.printStackTrace();
        }

    }


}

一个alaram服务继续运行或不运行

import android.app.Activitymanager;
import android.app.Intentservice;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class Alarmservice extends Intentservice {
    @Override
    protected void onHandleIntent(Intent intent) {
        Boolean isserviceRunning = false;
        Activitymanager manager = (Activitymanager) getSystemservice(Context.ACTIVITY_serviCE);
        for (Activitymanager.RunningserviceInfo service : manager.getRunningservices(Integer.max_value)) {
            if (Connectionservice.class.getName().equals(service.service.getClassName())) {
                isserviceRunning = true;
                break;
            }
        }
        Log.i("Alarmservice","service is running " + isserviceRunning);
        if(!isserviceRunning) {
            startservice(new Intent(getApplicationContext(),Connectionservice.class));
        } else {
            Connectionservice.checkConnectionAndConnect(getApplicationContext());
        }
    }

    /**
     * Creates an Intentservice.  Invoked by your subclass's constructor.
     */
    public Alarmservice() {
        super("Alaramservice");
    }
}

最后开始服务

private void checkAndStartservice() {
        final Activitymanager manager = (Activitymanager) getSystemservice(Context.ACTIVITY_serviCE);
        new AsyncTask<Void,Void,Boolean>() {
            Boolean isserviceRunning = false;

            @Override
            protected Boolean doInBACkground(Void... params) {
                for (Activitymanager.RunningserviceInfo service : manager.getRunningservices(Integer.max_value)) {
                    if (Connectionservice.class.getName().equals(service.service.getClassName())) {
                        isserviceRunning = true;
                        break;
                    }
                }
                return isserviceRunning;
            }

            @Override
            protected void onPostExecute(Boolean aBoolean) {
                super.onPostExecute(aBoolean);
                Log.i("onPostExecute","service running = " + aBoolean);
                if (!aBoolean) {
                    startservice(new Intent(ActivitySplash.this,Connectionservice.class));
                    Intent i = new Intent(ActivitySplash.this,Alarmservice.class);
                    PendingIntent pi = PendingIntent.getservice(ActivitySplash.this,i,0);
                    AlarmManager am = (AlarmManager) ActivitySplash.this.getSystemservice(Context.ALARM_serviCE);
                    am.cancel(pi); // cancel any exisTing alarms
                    am.setRepeaTing(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),60000,pi);
                }
            }
        }.execute();
    }

大佬总结

以上是大佬教程为你收集整理的android – 使用Google Play服务和FusedLocationProviderClient的位置更新全部内容,希望文章能够帮你解决android – 使用Google Play服务和FusedLocationProviderClient的位置更新所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。