首页 文章

如何使用android studio 6.0运行时权限使用MAP活动获取当前位置

提问于
浏览
0

公共类MapsActivity扩展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:在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)中只能对requestCode使用低8位在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.app.Looper.loop(Looper.java:148)的android.app.ActivityThread.main(ActivityThread.java:5443),位于java.lang.reflect.Method . 在com.android.internal.os.ZygoteInit.main(z)的com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:728)中调用(Native Method) ygoteInit.java:618)引起:java.lang.IllegalArgumentException:只能在android.support.v4.app的android.support.v4.app.FragmentActivity.validateRequestPermissionsRequestCode(FragmentActivity.java:799)的requestCode中使用低8位位于Android的com.vivanta.location.MapsActivity.onCreate(MapsActivity.java:39)的android.support.v4.app.ActivityCompat.requestPermissions(ActivityCompat.java:316)上的.ActivityCompatApi23.requestPermissions(ActivityCompat23.java:29) . android.app.ActivityThread.handleLaunchActivity上android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)的android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)上的app.Activity.performCreate(Activity.java:6245) (ActivityThread.java:2490)位于android.app.Handler.dispatchMessage(Handler.java)android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1354)的android.app.ActivityThread.-wrap11(ActivityThread.java) :102)在android.app.Ac的android.os.Looper.loop(Looper.java:148) tivityThread.main(ActivityThread.java:5443)位于com.android的com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:728)的java.lang.reflect.Method.invoke(Native Method)中 . internal.os.ZygoteInit.main(ZygoteInit.java:618)

1 回答

  • 0

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

    @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();
            }
        }
    }
    

相关问题