尽管处理Android M GPS权限,应用程序仍会崩溃

时间:2016-02-08 05:28:28

标签: android android-permissions android-6.0-marshmallow

我一直在使用Android M模型已经有一段时间了,但是最近我在移动设置中手动撤销了对位置和存储的权限,以查看该应用是否会在运行时再次询问用户的权限。从那以后,它一直在崩溃。请看一下我的代码 -

public class MapsActivity extends FragmentActivity implements com.google.android.gms.location.LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { 

    String[] perms={"android.permission.ACCESS_FINE_LOCATION","android.permission.WRITE_EXTERNAL_STORAGE"};
    int permsRequestCode = 200;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mGeofences = new ArrayList<Geofence>();
        mGeofenceCoordinates = new ArrayList<LatLng>();
//        double string0=prefenceSettings.getString("LatLng0", "34");

        setContentView(R.layout.activity_maps);
        showHelpForFirstLaunch();
        SupportMapFragment supportMapFragment =
                (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap);
        LocationManager locationManager = (LocationManager) getSystemService(Service.LOCATION_SERVICE);
        // getting GPS status
        boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if(!isGPSEnabled)
        {
            Utils.displayPromptForEnablingGPS(this);
        }
        Log.i("My activity", "gps is" + isGPSEnabled);

        // getting network status
        boolean isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        Log.i("My activity", "network is" + isNetworkEnabled);

        Criteria crta = new Criteria();
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD) {
            crta.setAccuracy(Criteria.ACCURACY_FINE);
        } else {
            crta.setAccuracy(Criteria.ACCURACY_MEDIUM);
        }
        /**
         * we have used .setAccuracy as fine for higher SDks than gingerbread .Gingerbread is used as a reference because in apks lower
         * than gingerbread there is very poor geo-fencing, with gingerbread google made it a lot easier for location services to be used for devleopers.
         * it had improved set of tools for Location Services, which included geofencing and substantially improved location discovery.
         */
        crta.setPowerRequirement(Criteria.POWER_LOW);
        String provider = locationManager.getBestProvider(crta, true);

        /**
         * It request Location updates after every 5 sec or if the user traveled 10m
         */
        Log.i("My activity", "manager is " + locationManager);
        Log.i("My activity", "provider is " + provider);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                requestPermissions(perms, permsRequestCode);
                // 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 Activity#requestPermissions for more details.
                return;
            }
        }
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks((GoogleApiClient.ConnectionCallbacks) this)
                    .addOnConnectionFailedListener((GoogleApiClient.OnConnectionFailedListener) this)
                    .addApi(LocationServices.API)
                    .build();
            mGoogleApiClient.connect();
            Log.i("Api is", "" + mGoogleApiClient);
        }
        mLocationRequest = new LocationRequest();
        // We want a location update every 10 seconds.
        mLocationRequest.setInterval(10000);
        // We want the location to be as accurate as possible.
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);



    }


    public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults){

        switch(permsRequestCode){

            case 200:

                boolean gpsAccepted = grantResults[0]==PackageManager.PERMISSION_GRANTED;
                Toast.makeText(this,"Thanks for the permission",Toast.LENGTH_SHORT).show();
                boolean memoryAccepted = grantResults[1]==PackageManager.PERMISSION_GRANTED;

                break;

        }

    }

    @Override
    public void onLocationChanged(Location location) {
        latitude=location.getLatitude();
        longitude=location.getLongitude();
        CameraPosition INIT =
                new CameraPosition.Builder()
                        .target(new LatLng(latitude, longitude))
                        .zoom(17.5F)
                        .bearing(300F) // orientation
                        .tilt(50F) // viewing angle
                        .build();
        // use GooggleMap mMap to move camera into position
        googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(INIT));
    }

    @Override
    protected void onStart() {

        super.onStart();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onStop() {

        super.onStop();
        mGoogleApiClient.disconnect();

    }


    public void Add(View view) {

        if (request < 3) {
            String[] arguments = new String[]{String.valueOf(request)};
            ContentValues values = new ContentValues();
            values.put("latitude", latitude);
            values.put("true","1");
            values.put("longitude", longitude);
            db.update("Coordinates", values, "id=?", arguments);

            mGeofenceCoordinates.add(new LatLng(latitude, longitude));
            Log.i("The id is", "" + valueindex);
            mGeofences.add(new Geofence.Builder()
                    // The coordinates of the center of the geofence and the radius in meters.
                    .setRequestId("" + valueindex)
                    .setCircularRegion(latitude, longitude, 100)
                    .setExpirationDuration(Geofence.NEVER_EXPIRE)
                            // Required when we use the transition type of GEOFENCE_TRANSITION_DWELL
                    .setLoiteringDelay(50000)
                    .setTransitionTypes(
                            Geofence.GEOFENCE_TRANSITION_ENTER
                                    | Geofence.GEOFENCE_TRANSITION_DWELL
                                    | Geofence.GEOFENCE_TRANSITION_EXIT).build());
            mGeofenceStore = new GeofenceStore(this, mGeofences);
            valueindex++;
            request++;




            googleMap.addMarker(new MarkerOptions().snippet("Radius:100m").draggable(false).title(valueindex + "").position(new LatLng(latitude, longitude))).showInfoWindow();
        } else {
            Toast.makeText(this, "Maximum limit exceeded", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        Location mlastlocation;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(perms, permsRequestCode);


                return;
            }
        }
        mlastlocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        startLocationUpdates();
        if (mlastlocation != null) {
            Log.i("the last location:", "" + mlastlocation);
//            Toast.makeText(this, "Get last location first asshole!", Toast.LENGTH_LONG).show();
        }


    }


    protected void startLocationUpdates() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(perms, permsRequestCode);

                return;
            }
            LocationRequest mLocationRequest = new LocationRequest();

            LocationServices.FusedLocationApi.requestLocationUpdates(
                    mGoogleApiClient, mLocationRequest, this);
        }
    }

       }

请帮我找几天了!我的清单文件很好,包括所有用户权限

1 个答案:

答案 0 :(得分:0)

你的错误就在这一行:

   String[] perms={"android.permission.ACCESS_FINE_LOCATION","android.permission.WRITE_EXTERNAL_STORAGE"};

将其更改为

   String[] perms={"android.permission.ACCESS_FINE_LOCATION","android.permission.ACCESS_COARSE_LOCATION"};