绝大多数情况一个APP不可能只有单个权限,往往需要运行时批量申请n多个权限。比如在Androidmanifest里面写了两个权限:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
那么在运行时申请权限,要点是把全部权限装入到一个String数据里面,批量做一次申请:
package zhangphil.permission;
import android.Manifest;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private final String TAG = "ZHANG PHIL";
private final int PERMISSION_REQUEST = 0xa00;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST:
if (grantResults != null && permissions != null) {
for (int i = 0; i < grantResults.length; i++) {
Log.d(TAG, "grantResults[" + i + "]:" + grantResults[i]);
Log.d(TAG, "permissions[" + i + "]:" + permissions[i]);
}
}
break;
}
}
}
代码运行结果logcat输出: 09-25 11:10:17.354 14247-14247/zhangphil.permission D/ZHANG PHIL: grantResults[0]:0
09-25 11:10:17.355 14247-14247/zhangphil.permission D/ZHANG PHIL: permissions[0]:android.permission.CAMERA
09-25 11:10:17.355 14247-14247/zhangphil.permission D/ZHANG PHIL: grantResults[1]:0
09-25 11:10:17.355 14247-14247/zhangphil.permission D/ZHANG PHIL: permissions[1]:android.permission.WRITE_EXTERNAL_STORAGE