如果已禁用,则检测GPS

时间:2017-11-13 12:56:12

标签: android android-location fusedlocationproviderapi android-fusedlocation

我想检测用户旅行,当旅行开始时,我必须每隔5秒钟获得一次LatLng。我正在使用Google FusedLocationAPI和我的问题是直到我的GPS启用然后它计算所有距离但是一旦我禁用GPS它被卡住了。如果用户在行程中途禁用GPS,我该如何显示待定行程?

我的服务类是:

public class TripStartedService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    public static long UPDATE_INTERVAL_IN_MILLISECONDS = 1000 * 5;
    public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
    public GoogleApiClient mGoogleApiClient;
    public LocationRequest mLocationRequest;

    private PendingIntent mPendingIntent;
    IBinder mBinder = new TripStartedService.LocalBinder();
    public static boolean isGPSOn = false;

    @Override
    public void onCreate() {
        super.onCreate();
        Intent mIntentService = new Intent(this, TripStartedIntent.class);
        mPendingIntent = PendingIntent.getService(this, 1, mIntentService, PendingIntent.FLAG_UPDATE_CURRENT);
        buildGoogleApiClient();
    }

    protected synchronized void buildGoogleApiClient() {
        Log.i("", "Building GoogleApiClient");
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        createLocationRequest();
    }

    private void createLocationRequest() {
        Log.i("TRIP_START_Request", "createLocationRequest()");
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onConnected(Bundle bundle) {
        startLocationUpdates();
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i("", "Connection suspended");
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.i("", "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
    }

    @Override
    public void onLocationChanged(Location location) {
        String message = "Latitude : " + location.getLatitude() + "\n Longitude : " + location.getLongitude() + "\n Accuracy: " + location.getAccuracy();
        Log.i("", "onLocationChanged: " + message);
    }


    private void startLocationUpdates() {
        Log.i("", "Started Location Updates");
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mPendingIntent);
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        LocationManager manager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        isGPSOn = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);


        if (mGoogleApiClient.isConnected()) {
            Log.i("GPS init" + " onStartCmd", "Connected");
            return START_STICKY;
        }

        if (!mGoogleApiClient.isConnected() || !mGoogleApiClient.isConnecting()) {
            Log.i("Connceti" + " onStartCmd", "GoogleApiClient not Connected");
            mGoogleApiClient.connect();
        }

        return START_STICKY;
    }

    private class LocalBinder extends Binder {
        public TripStartedService getServerInstance() {
            return TripStartedService.this;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopLocationUpdates();
    }

    public void stopLocationUpdates() {
        Log.i("", "Stopped Location Updates");
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mPendingIntent);
    }
} 

我的计算类是

 if (isGPSOn) {

            try {
                LocDatabaseHelper database = new LocDatabaseHelper(activity);
                Timestamp timestamp_start = new Timestamp(System.currentTimeMillis());
                Timestamp timestamp_end = new Timestamp(System.currentTimeMillis());

                final int TRIP_START_ID = 0;
                ContentValues contentValues = new ContentValues();


                final ArrayList<TripDistanceModels> trip_list_values = database.getTripDistance();

                try {
                    Location loc1 = new Location("");
                    loc1.setLatitude(Double.parseDouble(trip_list_values.get(0).getLatitude()));
                    loc1.setLongitude(Double.parseDouble(trip_list_values.get(0).getLongitude()));

                    Location loc2 = new Location("");
                    loc2.setLatitude(Double.parseDouble(trip_list_values.get(1).getLatitude()));
                    loc2.setLongitude(Double.parseDouble(trip_list_values.get(1).getLongitude()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                contentValues.put(TRIP_STARTED_ID, TRIP_START_ID);
                contentValues.put(TRIP_STARTED_LATTITUDE, start_trip_location.getLatitude());
                contentValues.put(TRIP_STARTED_LONGITUDE, start_trip_location.getLongitude());
                contentValues.put(TRIP_STARTED_TIMESTAMP, String.valueOf(timestamp_start));
                contentValues.put(TRIP_END_TIMESTAMP, String.valueOf(timestamp_end));
                database.tripInsertionOnDetect(TRIP_START_ID, start_trip_location.getLatitude(), start_trip_location.getLongitude(), timestamp_start, timestamp_end, "pending status");
                Log.d("TRIP STARTRED", contentValues.toString());

                final int trip_counts = database.getRowCountForTripStarted();
                final int back_counts = database.getRowCountForBackground();
                Log.e("TRip Database Rows Size", "" + trip_counts + "\t \tBackGroundTable Rows : " + back_counts + "\tGPS>>>: " + Boolean.toString(isGPSOn));
                activity.stopService(new Intent(activity, BackgroundLocationService.class));
            } catch (Exception e) {
                e.printStackTrace();
            }


        }

2 个答案:

答案 0 :(得分:0)

如果您的gps未启用,则可以使用手机信号塔位置。它不准确。你可以靠近地点。

if (isNetworkEnabled) {
           locationManager.requestLocationUpdates(
              LocationManager.NETWORK_PROVIDER,
              MIN_TIME_BW_UPDATES,
              MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

           Log.d("Network", "Network");
           if (locationManager != null) {
              location = locationManager
                 .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

              if (location != null) {
                 latitude = location.getLatitude();
                 longitude = location.getLongitude();
              }
           }
        }

答案 1 :(得分:0)

您应添加广播接收器以检测gps是启用还是禁用:

   private BroadcastReceiver gpsReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {
                LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
                boolean isGpsEnabled = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                if (intent.getAction().matches("android.location.PROVIDERS_CHANGED")) {

                    if (isGpsEnabled) {
                        //Here code when gps is enabled 

                    } else {
                        //Here code when gps is disabled 

                    }
                }
            }
        }
    };
@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        registerReceiver(gpsReceiver, new IntentFilter("android.location.PROVIDERS_CHANGED"));
       //here other code ...
        return super.onStartCommand(intent, flags, startId);
    }