应用程序因空指针异常而崩溃,并要求具有“访问精细位置”权限

时间:2018-09-24 06:43:08

标签: java android google-maps google-maps-api-3

我在应用程序中使用GPS,当我编译并运行应用程序时崩溃并显示错误消息

  

javal.lang.SecurityException:“ gps”位置提供程序需要ACCESS_FINE_LOCATOIN.permission

虽然我已经在“清单文件”中添加了权限。我还要求活动中提供运行时权限,但仍然出现错误

这是logcat的屏幕截图 enter image description here

gps方法

 private void checkGPS() {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))


 buildAlertMessageNoGps();
}

我的清单文件是

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.nepalpolice.cdp">

<uses-permission android:name="android.permissoin.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  

我的整个代码是

public class MapActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener,
        GoogleMap.OnInfoWindowClickListener, LocationListener {
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.v(TAG, "onCreate started");
        super.onCreate(savedInstanceState);
        setInternalStorage();

        // Read selected location from Extra of passed intent
        selectedLocationData = (LocationData) getIntent().getSerializableExtra(InternalStorage.SEL_LOC_DATA_KEY);
        if(selectedLocationData!=null)
            internalStorage.writeLocationData(selectedLocationData,TARGET_ID);

        checkGPS();
        checkAndConnect();

      




        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            this.googleMap.setMyLocationEnabled(true);
            googleApiClient = new GoogleApiClient.Builder(this)       // This code is for updating current location
                    .addApi(LocationServices.API)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .build();
            googleApiClient.connect();
            zoom(15, 90, 40);
            if (selectedLocationData != null && selectedLocationData.isReal()) {
                setMarker(selectedLocationData.getLatitude(), selectedLocationData.getLongitude());
                startLocationRequest(); // If location is passed from StartActivity, start checking locations
            }
            centerMap();
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_FINE_LOCATIONS);
            }
        }
    }

    private void zoom(float zoom, float bearing, float tilt) {
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
            if (location != null) {
                googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 13));
                CameraPosition cameraPosition = new CameraPosition.Builder()
                        .target(new LatLng(location.getLatitude(), location.getLongitude()))      // Sets the center of the map to location user
                        .zoom(zoom)                   // Sets the zoom
                        .bearing(bearing)                // Sets the orientation of the camera to east
                        .tilt(tilt)                   // Sets the tilt of the camera to 30 degrees
                        .build();                   // Creates a CameraPosition from the builder
                googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
            }
        }
    }

   

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_FINE_LOCATIONS:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                        googleMap.setMyLocationEnabled(true);
                        googleApiClient = new GoogleApiClient.Builder(this)       // This code is for updating current location
                                .addApi(LocationServices.API)
                                .addConnectionCallbacks(this)
                                .addOnConnectionFailedListener(this)
                                .build();
                        googleApiClient.connect();
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "this app requires location permissions to be granted", Toast.LENGTH_LONG).show();
                    ActivityCompat.finishAffinity(MapActivity.this);
                    System.exit(0);
                }
                break;
        }
    }

 
    private void buildAlertMessageNoWifi() {
   

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    void startLocationRequest() {
        checkGPS();
        isTracking = true;
        userNotified = false;
        interval = MIN_INTERVAL;
        internalStorage.writeInterval(interval);
        // Manage wake up alerts
        alarm = new AlarmReceiver();
        alarm.setAlarm(this, interval);
        renewLocationRequest();
        // Hide search options
        findViewById(R.id.button).setVisibility(View.GONE);
        findViewById(R.id.place_autocomplete_fragment).setVisibility(View.GONE);
        // Toggle tracking button view
        Button button = (Button) findViewById(R.id.startpause);
        button.setBackgroundColor(Color.RED);
        button.setText("Pause tracking");
        if (locationRequest != null) // TODO should check why it happens
            Log.v("startLocationRequest", "" +
                    "\ninterval:" + String.valueOf(locationRequest.getInterval()) +
                    "\nfastest interval:" + String.valueOf(locationRequest.getFastestInterval()));
    }

  
    void stopLocationRequest() {
        if (googleApiClient != null && googleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
            googleApiClient.disconnect();
        }
        locationRequest = null;
        isTracking = false;
        alarm.releaseWakeLock();
        alarm = null;
        Button button = (Button) findViewById(R.id.startpause);
        button.setBackgroundColor(Color.GREEN);
        button.setText("Start tracking");
        Log.i("stopLocationRequest", "stopped successfully");
    }

    public void enableWiFi() {
        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wifiManager.setWifiEnabled(true);
        startActivity(new Intent(WifiManager.ACTION_PICK_WIFI_NETWORK));
        Toast.makeText(getApplicationContext(), "Wi-fi connecting..", Toast.LENGTH_LONG).show();
    }

    private void checkGPS() {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
            buildAlertMessageNoGps();
    }

    public void checkAndConnect() {
        if (!checkedWiFi) {
            ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
            // test for connection
            if (cm != null) {
                if (!(cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected())) {
                    buildAlertMessageNoWifi();
                }
            }
            checkedWiFi = true;
        }
    }

   

请帮助

0 个答案:

没有答案