我想让我的应用程序在应用程序继续之前等待用户授予权限。我搜索了有关它的其他线程,发现常见的方法是使用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();
}
和请求结果:
@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();
慕的地10843
相关分类