禁用GPS后,用户应再次打开GPS。我怎样才能做到这一点?

时间:2019-01-28 01:44:14

标签: android google-maps android-studio gps

我想检测何时禁用gps。当用户禁用gps时,我想调用openGpsWindow()以提示用户再次启用它。返回后,gps应该会再次找到该位置。如何在代码中实现?预先感谢!

我的代码:

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {

    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;

    private static final float DEFAULT_ZOOM = 16f;

    public Boolean mLocationPermissionsGranted = false;

    private GoogleMap mMap;

    private FusedLocationProviderClient mFusedLocationProviderClient;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_maps);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

        mapFragment.getMapAsync(MapsActivity.this);


        getLocationPermission();

        //LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        //if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        //  openGpsWindow();
        //}


    }

    private void updateLocationUI() {
        if (mMap == null) {
            return;
        }
        try {
            if (mLocationPermissionsGranted) {
                getDeviceLocation();
            } else {
                mMap.setMyLocationEnabled(false);
                mMap.getUiSettings().setMyLocationButtonEnabled(false);
                getLocationPermission();
            }
        } catch (SecurityException e) {
            Log.e("Exception: %s", e.getMessage());
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {

        //map is ready
        mMap = googleMap;

        if (mLocationPermissionsGranted) {

            getDeviceLocation();


            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)

                    != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            //mMap.setMyLocationEnabled(true);
        }
    }

    private void getDeviceLocation() {

        // getting the device's current location

        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);


        if (mLocationPermissionsGranted) {

            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
            final Task location = mFusedLocationProviderClient.getLastLocation();

            location.addOnCompleteListener(new OnCompleteListener() {

                @Override
                public void onComplete(@NonNull Task task) {

                    if(task.isSuccessful() && task.getResult() != null){

                        //onComplete: found location

                        Location currentLocation = (Location) task.getResult();

                        double latitude = currentLocation.getLatitude();
                        double longitude = currentLocation.getLongitude();

                        //Finding user's location
                        LatLng myCoordinates = new LatLng(latitude, longitude);
                        moveCamera(myCoordinates, DEFAULT_ZOOM);

                        //Adding an icon marker to display the user's location and the info window from above
                        MarkerOptions marker = new MarkerOptions();
                        mMap.addMarker(marker.position(new LatLng(latitude, longitude)).icon(BitmapDescriptorFactory.fromResource(R.drawable.map_marker_mini))).showInfoWindow();

                    } else {
                        //unable to get current location
                    }
                }
            });
        }
    }

    private void moveCamera(LatLng latLng, float zoom) {

        //moveCamera: moving the camera to: lat: + latLng.latitude +  lng:  + latLng.longitude

        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
    }

    private void getLocationPermission() {

        if (ContextCompat.checkSelfPermission(this.getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

            mLocationPermissionsGranted = true;

        } else {
            ActivityCompat.requestPermissions(this,

                    new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},

                    LOCATION_PERMISSION_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {

        mLocationPermissionsGranted = false;

        switch (requestCode) {

            case LOCATION_PERMISSION_REQUEST_CODE: {

                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    mLocationPermissionsGranted = true;
                }
            }
        }

        updateLocationUI();

    }

    public void openGpsWindow() {
        Intent intent = new Intent(this, EnableGpsWindow.class);
        startActivity(intent);
    }
}

我想检测何时禁用gps。当用户禁用gps时,我想调用openGpsWindow()以提示用户再次启用它。返回后,gps应该会再次找到该位置。如何在代码中实现? 预先感谢!

1 个答案:

答案 0 :(得分:1)

您必须使用LocationListener以及OnMapReadyCallback来实现MapsActvity。在那里,您将找到位置侦听器的两种覆盖方法。

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback,LocationListener

然后只需按Alt + Enter,这些覆盖方法将自动添加。

 @Override
    public void onProviderDisabled(String provider) {
        Log.e("Location Tag", "Provider Disabled");
        openGpsWindow();
    }

    @Override
    public void onProviderEnabled(String provider) {
        Log.e("Location Tag", "Provider Enabled");

    }