2017-01-20 49 views
1

被拒绝,我需要在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

这不是一个错误。这是一个警告。林特无法说明您拨打myPermissionNeededMethod()的唯一地方是检查您是否拥有此权限。

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

否则,把你的文本光标在某处所给你的警告(即有红色或黄色undersquiggle)的代码,按Alt-Enter组合,并寻找一个快速修复,增加了一个@SuppressLint注释,告诉琳特停止抱怨这个问题。然后,确定您只有在确认已拥有此权限时才致电myPermissionNeededMethod(),由您决定。

相关问题