我正在开发一款创建里程表服务的Android教程:https://github.com/dogriffiths/HeadFirstAndroid/tree/master/chapter13/Odometer
看来我需要明确要求用户使用位置服务的权限。 https://developer.android.com/training/permissions/requesting.html
但这似乎是针对扩展ActivityCompat的活动。我的MainActivity扩展了Activity。
有没有人在扩展Activity类时有一个如何实现requestPermissions()的例子?它究竟会去哪里......在课堂上还是在onCreate上?
由于
答案 0 :(得分:0)
ContextCompat
是从android.support.v4库派生的公共类,它与AppCompatActivity无关。要检查Android版本23及更高版本的权限,您可以执行以下操作:
private void getPermission(String permission, Integer requestCode) {
if (ContextCompat.checkSelfPermission(test_activity.this, permission) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(test_activity.this, new String[]{permission}, requestCode);
} else {
Toast.makeText(this, "" + permission + " is already granted.", Toast.LENGTH_SHORT).show();
}
}
调用onCreate
中的方法:
getPermission(android.Manifest.permission.ACCESS_FINE_LOCATION, requestCode);
覆盖onRequestPermissionsResult
并处理结果:
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(ActivityCompat.checkSelfPermission(this, permissions[0]) == PackageManager.PERMISSION_GRANTED){
switch (requestCode) {
//Location
case 1:
// do something
break;
}
else
{
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
}