起因:当时用的测试机是运行android6.0,并且代码中使用
compileSdkVersion 23 buildToolsVersion '23.0.3'然后发现在调用图库获取图片时,返回资源总是为null,也无法向SD卡存入照片,检查清单文件中是已经配置了读写外部内存权限的。
最后成功的解决方法是:在当前Activity中添加以下代码,代码的作用是检查是否已经获取到所需要的权限,如果没有则再次请求权限
// Check whether we have write permission int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE); if (permission != PackageManager.PERMISSION_GRANTED) { // We don't have permission so prompt the user ActivityCompat.requestPermissions( this, PERMISSIONS_STORAGE,//需要请求的所有权限,这是个数组String[] REQUEST_EXTERNAL_STORAGE//请求码 ); }
原来是android6.0加强了对权限的管理,对于IDE使用API23及以上版本开发的APP运行在6.0及以上的系统时,敏感权限都需要在程序运行时进行动态获取,以上代码就是动态获取例子
请求权限的回调
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); }
普通权限:
- ACCESS_LOCATION_EXTRA_COMMANDS
- ACCESS_NETWORK_STATE
- ACCESS_NOTIFICATION_POLICY
- ACCESS_WIFI_STATE
- BLUETOOTH
- BLUETOOTH_ADMIN
- BROADCAST_STICKY
- CHANGE_NETWORK_STATE
- CHANGE_WIFI_MULTICAST_STATE
- CHANGE_WIFI_STATE
- DISABLE_KEYGUARD
- EXPAND_STATUS_BAR
- GET_PACKAGE_SIZE
- INSTALL_SHORTCUT
- INTERNET
- KILL_BACKGROUND_PROCESSES
- MODIFY_AUDIO_SETTINGS
- NFC
- READ_SYNC_SETTINGS
- READ_SYNC_STATS
- RECEIVE_BOOT_COMPLETED
- REORDER_TASKS
- REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
- REQUEST_INSTALL_PACKAGES
- SET_ALARM
- SET_TIME_ZONE
- SET_WALLPAPER
- SET_WALLPAPER_HINTS
- TRANSMIT_IR
- UNINSTALL_SHORTCUT
- USE_FINGERPRINT
- VIBRATE
- WAKE_LOCK
- WRITE_SYNC_SETTINGS
- CALENDAR(日历)
- READ_CALENDAR
- WRITE_CALENDAR
- CAMERA(相机)
- CAMERA
- CONTACTS(联系人)
- READ_CONTACTS
- WRITE_CONTACTS
- GET_ACCOUNTS
- LOCATION(位置)
- ACCESS_FINE_LOCATION
- ACCESS_COARSE_LOCATION
- MICROPHONE(麦克风)
- RECORD_AUDIO
- PHONE(手机)
- READ_PHONE_STATE
- CALL_PHONE
- READ_CALL_LOG
- WRITE_CALL_LOG
- ADD_VOICEMAIL
- USE_SIP
- PROCESS_OUTGOING_CALLS
- SENSORS(传感器)
- BODY_SENSORS
- SMS(短信)
- SEND_SMS
- RECEIVE_SMS
- READ_SMS
- RECEIVE_WAP_PUSH
- RECEIVE_MMS
- STORAGE(存储卡)
- READ_EXTERNAL_STORAGE
- WRITE_EXTERNAL_STORAGE