在開發(fā)安卓應(yīng)用時(shí),通過需要訪問SDCARD、外部存儲器。
當(dāng)遇到 這個錯誤時(shí),通常是由于以下幾種原因?qū)е碌模鉀Q方法如下:
1. AndroidManifest.xml文件中未定義以下權(quán)限: 解決方法是添加以下權(quán)限: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
2. 在調(diào)試的設(shè)備或模擬器中,App訪問Storage的權(quán)限是關(guān)閉的: 解決方法是: 在設(shè)置->應(yīng)用->找到并點(diǎn)擊你的應(yīng)用->權(quán)限->看到“存儲”或“Storage”這一項(xiàng)了吧,把它打開即可。
3. 從API 23開始,還需要通過代碼申請權(quán)限: // Storage Permissions private static final int REQUEST_EXTERNAL_STORAGE = 1; private static String[] PERMISSIONS_STORAGE = { android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE };
/** * Checks if the app has permission to write to device storage * * If the app does not has permission then the user will be prompted to grant permissions * * @param activity */ public static void verifyStoragePermissions(android.app.Activity activity) { // Check if we have write permission int permission = ActivityCompat.checkSelfPermission(activity, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != android.content.pm.PackageManager.PERMISSION_GRANTED) { // We don't have permission so prompt the user ActivityCompat.requestPermissions( activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE ); } }
|