Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用具有android studio 6.0运行时权限的地图活动获取当前位置_Android_Google Maps_Android Studio - Fatal编程技术网

如何使用具有android studio 6.0运行时权限的地图活动获取当前位置

如何使用具有android studio 6.0运行时权限的地图活动获取当前位置,android,google-maps,android-studio,Android,Google Maps,Android Studio,公共类MapsActivity扩展了FragmentActivity在MapReadyCallback上的实现{ 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 onCrea

公共类MapsActivity扩展了FragmentActivity在MapReadyCallback上的实现{

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:致命异常:main 进程:com.vivanta.location,PID:15330 java.lang.RuntimeException:无法启动活动组件信息{com.vivanta.location/com.vivanta.location.MapsActivity}:java.lang.IllegalArgumentException:只能对请求代码使用较低的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) 位于java.lang.reflect.Method.invoke(本机方法) 在com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)上 位于com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 原因:java.lang.IllegalArgumentException:只能对请求代码使用较低的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) 位于java.lang.reflect.Method.invoke(本机方法) 在com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)上
在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

将整个
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();
        }
    }
}