无法在Android

时间:2018-10-03 16:33:32

标签: android google-play-services android-service

我正在使用Google Play服务启动位置服务,但无法正常工作。它不适用于棉花糖和更高版本。权限没有问题,也没有错误,但是没有传递位置更新。

任何帮助将不胜感激。

这是我的服务等级文件:

package com.Myapp.services;

    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.FusedLocationProviderClient;
    import com.google.android.gms.location.LocationCallback;
    import com.google.android.gms.location.LocationListener;
    import com.google.android.gms.location.LocationRequest;
    import com.google.android.gms.location.LocationResult;
    import com.google.android.gms.location.LocationServices;
    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.location.LocationManager;
    import android.os.Bundle;
    import android.os.IBinder;
    import android.provider.Settings;
    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.location.LocationRequest;
    import com.Loadmandi.Activities.DashboardActivity;
    import com.Loadmandi.Api.LocationApi;

    import java.util.Timer;
    import java.util.TimerTask;

    public class LocationService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
        String TAG = "ConnectionService";

        FusedLocationProviderClient mFusedLocationClient;
        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;
            LocationApi.stopLocation(getApplicationContext());
            super.onDestroy();
            stopLocationUpdates();
        }

        private void setupLocationService(Context context) {
                mGoogleApiClient = new GoogleApiClient.Builder(context)
                        .addApi(LocationServices.API)
                        .addConnectionCallbacks(this)
                        .addOnConnectionFailedListener(this)
                        .build();
                         createLocationRequest();

        }

        protected void createLocationRequest() {
            mLocationRequest = new LocationRequest();
            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 void startLocationUpdates() {
            if (mGoogleApiClient.isConnected()) {
                Log.w(TAG, "in startLocationUpdates");

                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
             FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
                mFusedLocationClient.requestLocationUpdates(mLocationRequest,mLocationCallback,null);
            }
        }


        @Override
        public void onConnected(@Nullable Bundle bundle) {
            Log.w(TAG, "Connected to onConnected");
            startLocationUpdates();
        }

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

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

       LocationCallback mLocationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                if (locationResult == null) {
                    Log.w(TAG, "165 location is null");
                    return;
                }else{
                    Log.w(TAG, "167 location is not null");
                }
                for (Location location : locationResult.getLocations()) {
                    // Update UI with location data
                    LocationApi.sendGpsLocation(getApplicationContext(),location.getLongitude(),location.getLatitude());
                }
            };
        };

        private void stopLocationUpdates() {
            mFusedLocationClient.removeLocationUpdates(mLocationCallback);
        }

    }

我正在通过以下代码从我的活动开始服务:

Intent i = new Intent(getApplicationContext(), LocationService.class);
                startService(i);

1 个答案:

答案 0 :(得分:0)

基于documentation

  

在请求位置更新之前,您的应用必须连接到位置   服务并提出位置请求。 Changing Location Settings的课程   向您展示如何执行此操作。提出位置请求后,您可以   通过调用开始常规更新   requestLocationUpdates()

     

本课向您展示如何使用   LocationCallback   回调方法。呼叫   requestLocationUpdates(),   将它传递给您的实例   LocationRequest   对象和一个   LocationCallback。   定义一个startLocationUpdates()方法,如下所示   代码示例:

 @Override protected void onResume() {
    super.onResume();
     if (mRequestingLocationUpdates) {
         startLocationUpdates();
     } }

 private void startLocationUpdates() {
     mFusedLocationClient.requestLocationUpdates(mLocationRequest,
             mLocationCallback,
             null /* Looper */); }