我正在编写代码以从位置管理器获取 lastknownlocation,这促使我添加运行时权限。
这是我的代码:
public class MainActivity extends AppCompatActivity implements LocationListener {
LocationManager locationManager;
String provider;
private final int MY_PERMISSIONS_REQUEST_CODE=1;
Location location;
Boolean isPermissionGranted=false;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(new Criteria(), false);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},MY_PERMISSIONS_REQUEST_CODE);
}
// return;
}
}
public void getlastknownposition()
{
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == MY_PERMISSIONS_REQUEST_CODE)
{
if(grantResults[0]==PackageManager.PERMISSION_GRANTED && grantResults[1]==PackageManager.PERMISSION_GRANTED){
Toast.makeText(MainActivity.this," granted "+grantResults[0]+"granted2"+grantResults[1], Toast.LENGTH_SHORT).show();
location = locationManager.getLastKnownLocation(provider);}
}
}
}
我仍然收到错误“呼叫需要用户可能拒绝的权限:代码应显式检查权限是否可用(使用checkPermission
)或显式处理潜在SecurityException
的onRequestPermissionsResult
在线location = locationManager.getLastKnownLocation(provider);