來源:大牛直播內部代碼android
請求權限:app
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
代碼:spa
/** * 根據目錄建立文件夾 * @param context * @param cacheDir * @return */ public static File getOwnCacheDirectory(Context context, String cacheDir) { File appCacheDir = null; //判斷sd卡正常掛載而且擁有權限的時候建立文件 if ( Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) && hasExternalStoragePermission(context)) { appCacheDir = new File(Environment.getExternalStorageDirectory(), cacheDir); Log.i(TAG, "appCacheDir: " + appCacheDir); } if (appCacheDir == null || !appCacheDir.exists() && !appCacheDir.mkdirs()) { appCacheDir = context.getCacheDir(); } return appCacheDir; } /** * 檢查是否有權限 * @param context * @return */ private static boolean hasExternalStoragePermission(Context context) { int perm = context.checkCallingOrSelfPermission("android.permission.WRITE_EXTERNAL_STORAGE"); return perm == 0; }