Prevent file deletion in Android

My application will write some files to the storage that will be used by the application when used (for example, config). This configuration is time-dependent and will be replaced by the application if necessary.

I am currently writing this on an SD card using Environment.getExternalStorageDirectory (). But this is visible when the user used the file browser and could be deleted.

Is it possible to prevent the prevention of file deletion other than the application itself?

I tried using Environment.getDataDirectory (), but I do not have permission to write there. Is there another way?

+4
source share
4 answers

Yes. Instead of saving it in a public place, such as an SD card, write your file in the application’s private space (internal storage), for example:

FileOutputStream fos = openFileOutput("myfile.dat", Context.MODE_PRIVATE); fos.write( WebnetTools.serializeObject( sec ) ); fos.close(); 

See the docs for more details . Be sure that it is NOT equivalent to an SD card due to the limited space that you got there.

+1
source

If recording to an SD card is not a requirement, you can write to the phone’s internal storage to make data private for your application.

0
source

Thanks for all the tips. I used android: sharedUserId in the android manifest and now I can write through the application’s internal memory.

Since my only goal is to write text files (no sharing, etc.), I found this the easiest to implement.

0
source

Try the following:

 File folder = context.getDir("images", Context.MODE_WORLD_WRITEABLE); File img = new File(folder, "img_"+widget_id+"_"+position+".png"); try{ FileOutputStream out = new FileOutputStream(img); b.compress(Bitmap.CompressFormat.PNG, 100, out); b.recycle(); internal_img = img.getPath(); }catch(Exception e){ e.printStackTrace(); } 

getDir create a folder in the internal memory that you can write, whatever you want inside, do not prevent deletion on the SD card. Also, if the SD card is disconnected, you cannot read / write your files.

-1
source

All Articles