Java 如何在关闭应用程序之前保存和恢复位图
我想为应用程序的用户制作可替换的个人背景。当他们更改图片时,我无法在关闭应用程序之前保存它。我尝试共享首选项,但不使用位图。如何在关闭应用程序之前保存和恢复位图Java 如何在关闭应用程序之前保存和恢复位图,java,android,android-studio,Java,Android,Android Studio,我想为应用程序的用户制作可替换的个人背景。当他们更改图片时,我无法在关闭应用程序之前保存它。我尝试共享首选项,但不使用位图。如何在关闭应用程序之前保存和恢复位图 //use this method to save your bitmap, call this method when you have bitmap private void saveBitmap(Bitmap pBitmap){ ContextWrapper contextWrapper = new ContextWrap
//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!");
我用以下代码保存文件路径:SharedPreferences.Editor=SharedPreferences.edit();editor.putString(“image_key”,filePath);--我保存文件路径编辑器.commit();super.onPause();尝试使用以下代码从save Preferences获取代码后,sharedpreferences=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());pFilePath=SharedReferences.getString(“resim_anahtari”,“”);但是它不起作用。你的密钥不同,保存和从SharedReference获取价值,请更正。我添加了保存和检索路径的答案。这很有效!谢谢你帮助我。对不起,我的错,我错过了那部分。