Android-请求运行时权限 [英] Android - Requesting Runtime Permissions
本文介绍了Android-请求运行时权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图了解如何在Android中为危险权限"(例如位置)请求运行时权限.
I am trying to understand how to request Runtime Permissions in android for "Dangerous permissions" like Location.
我了解的是,代码应该像这样
What i understand is that the code should go like this
public void checkPermission(){
if (ActivityCompat.checkSelfPermission(..) == PackageManager.PERMISSION_GRANTED){
getLocation();
} else {
ActivityCompat.requestPermissions(..);
}
}
public void onRequestPermissionsResult(..){
switch (requestCode) {
case MY_PERMISSIONS_REQUEST: {
if (..) {
// permission was granted, yay!
getLocation();
} else {
// permission denied, boo!
}
return;
}
}
}
public Location getLocation(){
locationManager.requestLocationUpdates(..)
..
}
问题是,这段代码给我locationManager
错误,告诉我我必须请求位置权限
The thing is, this code gives me error on locationManager
telling me i have to request the location permission
那么这个序列的问题是什么?
So what is the proplem with this sequence?
推荐答案
尝试一下,它对我有用
private void checkPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSIONS_REQUEST_FINE_LOCATION);
} else {
getLocation();
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_FINE_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
getLocation();
} else {
// permission denied, boo! Disable the
}
return;
}
}
}
这篇关于Android-请求运行时权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文