In general our mobile app default storage space is the memory of the phone, but for larger files such as video, audio, we can store it in SDcard:
Next, the code is implemented to store the files in SDcard (only the core code is implemented).
First, because we want to store in SDcard, we need to provide SDcard permissions:
To add permissions in Androidmanifest.xml:
<!--Create and delete file permissions in SDcard--><uses-permission android:name= "Android.permission.MOUNT_FORMAT_FILESYSTEMS"/ ><!--Write Data permissions to SDcard--><uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>
Then, add a method in the Fileservice.java:
public void Savetosdcard (String filename,string content) throws Exception{//environment.getexternalstoragedirectory ( ) function is to obtain the path of the SDcard file File = new file (environment.getexternalstoragedirectory (), filename);//Open the output stream FileOutputStream OutStream = new FileOutputStream (file);//write Content Outstream.write (Content.getbytes ()); Outstream.close ();}
The point is: environment.getexternalstoragedirectory () function
Finally, after clicking the "Save" button, we call the button's OnClick () method, which is added in this method:
New a Fileservice object, Getapplicationcontext () returns the context of the application, the life cycle is the entire application, and the application destroys it to destroy fileservice service = new Fileservice ( Getapplicationcontext ()); try { //To determine if the sdcard exists, and can read and write,//environment.getexternalstoragestate () Gets the current state://environment.media_ Mounted represents the state of SDcard: Presence Sdcardif (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) { Service.savetosdcard (filename, content); Call the Save () method to save the file Toast.maketext (Getapplicationcontext (), r.string.success, 1). Show (); Call a Toast to render a "save complete" message}else{toast.maketext (Getapplicationcontext (), R.string.sdcarderror, 1). Show ();// Call a Toast to render a "sdcard non-existent or write-protected" message}} catch (Exception e) {toast.maketext (Getapplicationcontext (), R.string.fail, 1). Show (); Call Toast object to render a "save failed" message E.printstacktrace ();}
Android Development Series (vii): Store files in SDcard