我想让我的应用程序在继续运行之前等待用户给予许可。我搜索了其他线程,发现常见的方法是使用onRequestPermissionResult
。现在,我几乎一无所知如何进行设置:我只是将程序代码放入请求onRequestPermissionResult
中,还是请求本身,还是需要进行设置,因此要求用户提供该应用程序和应用程序之后继续吗?
这是我的代码:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 123);
} else {
progressBar.setVisibility(View.VISIBLE);
GPSTracker gt = new GPSTracker(getActivity().getApplicationContext());
Location location = gt.getLocation();
if (location == null) {
Toast.makeText(getActivity(), "No location found.",
Toast.LENGTH_LONG).show();
} else {
lat = location.getLatitude();
lon = location.getLongitude();
}
new GetContacts().execute();
}
} else {
progressBar.setVisibility(View.VISIBLE);
GPSTracker gt = new GPSTracker(getActivity().getApplicationContext());
Location location = gt.getLocation();
if (location == null) {
Toast.makeText(getActivity(), "No location found.",
Toast.LENGTH_LONG).show();
} else {
lat = location.getLatitude();
lon = location.getLongitude();
}
new GetContacts().execute();
}
和RequestResult:
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 123: {
// If request is cancelled, the result arrays are empty
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
progressBar.setVisibility(View.VISIBLE);
GPSTracker gt = new GPSTracker(getActivity().getApplicationContext());
Location location = gt.getLocation();
if (location == null) {
Toast.makeText(getActivity(), "No location found.",
Toast.LENGTH_LONG).show();
} else {
lat = location.getLatitude();
lon = location.getLongitude();
}
new GetContacts().execute();
} else {
//Toast
}
return;
}
}
}
答案 0 :(得分:1)
就像评论中提到的马丁·齐特勒一样,您必须为棉花糖上方和下方的两个API做好准备,例如:
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, 123);
} else {
//GPS method
}
} else {
//GPS method
}
就像您在onRequestResult问题中提到的那样:
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 123: {
// If request is cancelled, the result arrays are empty
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//GPS method
} else {
// Toast for user
}
return;
}
}
}