应用程序如果要申请多个权限,建议在程序的入口就把所有的权限申请好,省得后面一个一个去申请麻烦。一开始我直接使用搜索到的权限工具类,结果很不幸,程序挂了,有可能我申请的权限太多吧。废话不多说,阿凯教你一步一步把Android6.0权限申请下来:
注意事项:.普通权限不用申请,危险权限需要申请(危险权限申请一组中的一个默认获得整一组的权限),系统权限没法申请。(如果不知道哪些是普通权限,哪些是危险权限请对照这个链接http://blog.csdn.net/chenlinfeng772885775/article/details/53508204。)
1.在ManAndroidManifest.xml注册需要申请的权限;
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2.在build.gradle文件中引入google easypermission框架
dependencies { compile 'pub.devrel:easypermissions:0.4.2' }
3.在程序入口的Activity实现EasyPermissions.PermissionCallbacks接口,搞定。
public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks { private static final int num = 123;//用于验证获取的权 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); requireSomePermission();// 申请权限 } @AfterPermissionGranted(num) private void requireSomePermission() { String[] perms = {
// 把你想要申请的权限放进这里就行,注意用逗号隔开
Manifest.permission.CALL_PHONE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_NETWORK_STATE, }; if (EasyPermissions.hasPermissions(this, perms)) { // Already have permission, do the thing // ... Toast.makeText(this, "Permissions Granted!", Toast.LENGTH_LONG).show(); } else { // Do not have permissions, request them now EasyPermissions.requestPermissions(this, getString(R.string.rationale_phone), num, perms); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); // EasyPermissions handles the request result. EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this); } @Override public void onPermissionsGranted(int requestCode, Listperms) { //Toast.makeText(this, "Permissions Granted!", Toast.LENGTH_LONG).show(); } @Override public void onPermissionsDenied(int requestCode, List perms) { //Toast.makeText(this, "Permissions Denied!", Toast.LENGTH_LONG).show(); } }
参考链接:https://github.com/googlesamples/easypermissions