首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android 拍照存儲:SD 卡不存在處理與 SharedPreferences 遷移方案

     編輯:程式設計綜合問答

SD 卡狀態檢測

public boolean hasExternalStorage() {
    return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
}

// 獲取可用存儲目錄(優先外部,回退內部)
public File getAppStorageDir(Context context, String dirName) {
    File file = new File(context.getExternalFilesDir(null), dirName);
    if (!file.exists() && !hasExternalStorage()) {
        file = new File(context.getFilesDir(), dirName); // 內部存儲
    }
    if (!file.exists()) file.mkdirs();
    return file;
}

拍照 Intent 兼容寫法

File photoFile = File.createTempFile("IMG_", ".jpg", getAppStorageDir(this, "photos"));
Uri photoUri = FileProvider.getUriForFile(this, getPackageName() + ".provider", photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

需在 Manifest 宣告 FileProvider。

SharedPreferences 遷移至自定義文件

// 讀取舊 SP
SharedPreferences oldSp = getSharedPreferences("login", MODE_PRIVATE);
String token = oldSp.getString("token", "");

// 寫入新文件(內部存儲,應用專屬,用戶不可見)
File tokenFile = new File(getFilesDir(), "auth_token.txt");
try (FileWriter fw = new FileWriter(tokenFile)) {
    fw.write(token);
}

// 登錄時讀取
String savedToken = new String(Files.readAllBytes(tokenFile.toPath()));

關鍵優勢

  • 內部存儲(/data/data/pkg/files/)無需權限,用戶無法手動清除
  • FileProvider 解決 Android 7+ Uri 暴露問題
  • 自定義文件格式靈活(JSON、加密二進制)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved