Я хочу сделать сменный личный фон для пользователей приложения. Когда они меняют картинку, я не могу сохранить ее до закрытия приложения. Я пробую общие настройки, но не работаю с растровым изображением. Как я могу сохранить и восстановить растровое изображение перед закрытием приложения?

0
Destiny 29 Сен 2020 в 20:50

1 ответ

Лучший ответ
//use this method to save your bitmap, call this method when you have bitmap
private void saveBitmap(Bitmap pBitmap){
    ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
    File directory = contextWrapper.getDir("folderName", Context.MODE_PRIVATE);
    if (!directory.exists()) {
        directory.mkdirs();
    }
    File file = new File(directory, "fileName.png");
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(file);
        pBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.close();
        String filePath = file.getAbsolutePath();
        //save this path in shared preference to use in future.
    } catch (Exception e) {
        Log.e("SAVE_IMAGE", e.getMessage(), e);
    }
}

Используйте этот метод, чтобы получить растровое изображение из пути к файлу, который вы сохранили

private void getBitmapFromPath(String pFilePath) {
    try {
        File f = new File(pFilePath);
        Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(f));
        //use this bitmap as you want
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

Для сохранения и получения пути к файлу

    //This for saving file path 
    PreferenceManager.getDefaultSharedPreferences(context).edit().putString("FILE_PATH_KEY", filePath).apply();

    //this for getting saved file path
    String filePath = PreferenceManager.getDefaultSharedPreferences(context).getString("FILE_PATH_KEY", "path not retrieved successfully!");
1
Abdur Rehman 5 Окт 2020 в 05:00