Marshmallow上的setMyLocationEnabled

时间:2016-03-10 12:05:02

标签: google-maps location android-6.0-marshmallow

我最近开始编程,我试图在android 6.0 Marshmallow中启用位置按钮来创建基本的地图应用程序。 我想我已经理解了新权限模型是如何工作的。当我运行应用程序时,它会要求我提供位置权限,但是,当我提供它时,位置按钮不会出现。如果我重新启动应用程序它已经出现。 我将把我的onMapReady方法的代码:

@Override
public void onMapReady(GoogleMap map) {


    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
       map.setMyLocationEnabled(true);
    } else {
        // Show rationale and request permission.
        Toast toast = Toast.makeText(this, "need permission", Toast.LENGTH_LONG);
        toast.show();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 0);
        }

    }
    map.setMyLocationEnabled(true);

}

我试图更改其他内部的最后一个setMyLocationEnabled但它没有用。我知道这是一个有点愚蠢的问题,但我不知道如何解决它。 希望可以有人帮帮我。提前致谢

1 个答案:

答案 0 :(得分:1)

您可以添加以下代码。

在早期版本的Android中,在安装时,它会向用户显示权限对话框,并且会将清单文件中的已定义权限授予应用程序。

在棉花糖中发生了变化。现在,每个应用程序都必须要求用户许可才能访问它。

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M)
{
    System.out.println("CHECK_RUN_TIME_PERMISSION_IF_MARSHMELLOW");
    if(!checkPermission()) {
        requestPermission();
    }else {
        System.out.println("CHECK_RUN_TIME_PERMISSION_IF_MARSHMELLOW++");
    }
}

private boolean checkPermission(){
    int result = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION);
    if (result == PackageManager.PERMISSION_GRANTED){

        return true;

    } else {

        return false;
   }
  }


private void requestPermission(){

    if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,Manifest.permission.ACCESS_FINE_LOCATION)){

        Toast.makeText(MainActivity.this,"GPS permission allows us to access location data. Please allow in App Settings for additional functionality.",Toast.LENGTH_LONG).show();
        ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},PERMISSION_REQUEST_CODE);

    } else {
        ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},PERMISSION_REQUEST_CODE);
    }
  }

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_REQUEST_CODE:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                Toast.makeText(MainActivity.this,"Permission Granted, Now you can access location data.",Toast.LENGTH_LONG).show();


            } else {

                Toast.makeText(MainActivity.this,"Permission Denied, You cannot access location data.",Toast.LENGTH_LONG).show();

            }
            break;
    }
}