如何使用android studio 6.0运行时权限

时间:2016-02-25 11:36:42

标签: android google-maps android-studio

public class MapsActivity extends FragmentActivity实现了OnMapReadyCallback {

private GoogleMap mMap;
private Location myLocation;
private static final int INITIAL_REQUEST=1337;
private static final int LOCATION_REQUEST=INITIAL_REQUEST+3;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);

    // Get Current Location

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}


/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

   /* // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(-34, 151);
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));*/
    mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("Snippet"));

    // Enable MyLocation Layer of Google Map
    mMap.setMyLocationEnabled(true);

    // Get LocationManager object from System Service LOCATION_SERVICE
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    // Create a criteria object to retrieve provider
    Criteria criteria = new Criteria();

    // Get the name of the best provider
    String provider = locationManager.getBestProvider(criteria, true);

    // Get Current Location
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_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)
        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},LOCATION_REQUEST);

        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    Location myLocation = locationManager.getLastKnownLocation(provider);

    // set map type
    mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    // Get latitude of the current location
    double latitude = myLocation.getLatitude();

    // Get longitude of the current location
    double longitude = myLocation.getLongitude();

    // Create a LatLng object for the current location
    LatLng latLng = new LatLng(latitude, longitude);

    // Show the current location in Google Map
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

    // Zoom in the Google Map
    mMap.animateCamera(CameraUpdateFactory.zoomTo(14));
    mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!").snippet("Consider yourself located"));

}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,int[] grantResults){
    switch (requestCode) {
        case LOCATION_REQUEST: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                doLocationThing();
                // permission was granted, yay! Do the
                // contacts-related task you need to do.


            } else {
                bzzzt();
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}
private void doLocationThing() {
    Toast.makeText(this, "Loacation fetched", Toast.LENGTH_SHORT).show();
}
private void bzzzt() {
    Toast.makeText(this, "not found", Toast.LENGTH_LONG).show();
}

}

错误D / AndroidRuntime:关闭VM 02-25 16:31:40.313 15330-15330 / com.vivanta.location E / AndroidRuntime:FATAL EXCEPTION:main                                                                       过程:com.vivanta.location,PID:15330                                                                       java.lang.RuntimeException:无法启动活动ComponentInfo {com.vivanta.location / com.vivanta.location.MapsActivity}:java.lang.IllegalArgumentException:对于requestCode只能使用低8位                                                                           在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)                                                                           在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)                                                                           在android.app.ActivityThread.-wrap11(ActivityThread.java)                                                                           在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1354)                                                                           在android.os.Handler.dispatchMessage(Handler.java:102)                                                                           在android.os.Looper.loop(Looper.java:148)                                                                           在android.app.ActivityThread.main(ActivityThread.java:5443)                                                                           at java.lang.reflect.Method.invoke(Native Method)                                                                           在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:728)                                                                           在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)                                                                        引起:java.lang.IllegalArgumentException:对于requestCode只能使用低8位                                                                           在android.support.v4.app.FragmentActivity.validateRequestPermissionsRequestCode(FragmentActivity.java:799)                                                                           在android.support.v4.app.ActivityCompatApi23.requestPermissions(ActivityCompat23.java:29)                                                                           在android.support.v4.app.ActivityCompat.requestPermissions(ActivityCompat.java:316)                                                                           在com.vivanta.location.MapsActivity.onCreate(MapsActivity.java:39)                                                                           在android.app.Activity.performCreate(Activity.java:6245)                                                                           在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)                                                                           在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)                                                                           在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)                                                                           在android.app.ActivityThread.-wrap11(ActivityThread.java)                                                                           在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1354)                                                                           在android.os.Handler.dispatchMessage(Handler.java:102)                                                                           在android.os.Looper.loop(Looper.java:148)                                                                           在android.app.ActivityThread.main(ActivityThread.java:5443)                                                                           at java.lang.reflect.Method.invoke(Native Method)                                                                           在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:728)                                                                           在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

1 个答案:

答案 0 :(得分:0)

使用onMapReady函数包裹整个runtimePermissionsRequest函数,如:

@Override
public void onMapReady(GoogleMap googleMap) {
    if(!runtimePermissionsReqest()){
      // your entire code here.
    }
}


private boolean runtimePermissionsRequest() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
            ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
            ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[]{
                android.Manifest.permission.ACCESS_FINE_LOCATION,
                android.Manifest.permission.ACCESS_COARSE_LOCATION}, 100);
        return true;
    }
    return false;
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == 100) {
        if (grantResults[0] != PackageManager.PERMISSION_GRANTED &&
                grantResults[1] != PackageManager.PERMISSION_GRANTED) {
            runtimePermissionsRequest();
        }
    }
}