呼叫需要权限,可能被用户拒绝

时间:2017-01-20 17:20:54

标签: android location

我需要在android中获取位置.... 我写这段代码:

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

            if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
                    !=PackageManager.PERMISSION_GRANTED)
            {
                if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,Manifest.permission.ACCESS_FINE_LOCATION))
                {
                    Toast.makeText(MainActivity.this,"Comment...",Toast.LENGTH_LONG).show();
                }
                else
                {
                    ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
                }
            }
            else
            {
                //Call whatever you want
                myPermissionNeededMethod();
            }
        }

    });
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode){
        case 1: {
            if((grantResults.length>0) && grantResults[0]==PackageManager.PERMISSION_GRANTED)
                myPermissionNeededMethod();
            else{
                // the user deny to giving permission so we ask him again or whatever we need to do !
            }
            return;

        }
    }
}

在myPermissionNeededMethod()中写道:

    public  void  myPermissionNeededMethod(){
    LocationManager locationManager =  (LocationManager) getSystemService(LOCATION_SERVICE);
    Location location= locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

}

但我再次收到错误调用需要许可,可能会被用户拒绝.... !!!! 如果我不能使用myPermissionNeededMethod()方法,我应该在oncreate和onRequestPermissionsResult的其他部分复制代码.... !!!

1 个答案:

答案 0 :(得分:1)

这不是错误。这是一个棉绒警告。 Lint无法判断您拨打myPermissionNeededMethod()的唯一地方是否正在检查您是否拥有此权限。

制作此方法private可能有所帮助。

否则,将文本光标放在给出警告的代码中(即,红色或黄色的下划线),按 Alt-Enter ,然后查找快速修复添加@SuppressLint注释,告诉Lint停止抱怨此问题。然后,您需要确保只有在确定已拥有此权限时才调用myPermissionNeededMethod()