Android piles of RuntimePermissions requests, code improving
for example:
AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.CAMERA" />
java:
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private final String TAG = "权限";
//请求码。
private final int REQUEST_CODE = 0xa01;
//批量权限组。
private String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
for (int i = 0; i < permissions.length; i++) {
if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, permissions[i] + "未获得授权,请求权限...");
ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE);
} else {
Log.d(TAG, permissions[i] + "已获得授权,无需重复请求权限。");
}
}
} else {
Log.d(TAG, "Android版本低于23,无需运行时请求权限。");
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE:
if (grantResults != null && permissions != null) {
for (int i = 0; i < grantResults.length; i++) {
/**
* PackageManager.PERMISSION_GRANTED:该值为常量值0,表示权限已经授予。
*/
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, permissions[i] + " 获得授权。");
//在这里开始启动获得授权后的业务逻辑代码。
}
/**
* PackageManager.PERMISSION_DENIED:该值为常量值-1,表示权限未被授予。
*/
if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
Log.d(TAG, permissions[i] + " 未获得授权。");
//在这里开始启动未获得授权后的业务逻辑代码。
}
}
}
break;
}
}
}