2017-01-20 50 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(),由您決定。

相關問題