2016年8月1日 星期一

External storage

Basic:

have private and public, if private,when the app delete,the file will be deleted too. Save at both place ,other application can read too.

Important:

it is because the external storage will be hang up,so when to read or write , we need to check first

How to check:


Environment.getExternalStorageState()

Summary
Constants
String MEDIA_BAD_REMOVAL
Storage state if the media was removed before it was unmounted.
String MEDIA_CHECKING
Storage state if the media is present and being disk-checked.
String MEDIA_EJECTING
Storage state if the media is in the process of being ejected.
String MEDIA_MOUNTED
Storage state if the media is present and mounted at its mount point with read/write access.
String MEDIA_MOUNTED_READ_ONLY
Storage state if the media is present and mounted at its mount point with read-only access.
String MEDIA_NOFS
Storage state if the media is present but is blank or is using an unsupported filesystem.
String MEDIA_REMOVED
Storage state if the media is not present.
String MEDIA_SHARED
Storage state if the media is present not mounted, and shared via USB mass storage.
String MEDIA_UNKNOWN
Unknown storage state, such as when a path isn't backed by known storage media.
String MEDIA_UNMOUNTABLE
Storage state if the media is present but cannot be mounted.
String MEDIA_UNMOUNTED
Storage state if the media is present but not mounted.

Permission need:

write
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
read:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />



Write:

//        if private
        File externalDir = this.getExternalFilesDir(null);

//        if public
//        File externalPublicDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);

        File file = new File(externalDir, name);

FileOutputStream outPutStraem = new FileOutputStream(file, false);
            outPutStraem.write(input.getBytes());
            outPutStraem.close();

Read:


File externalDir = this.getExternalFilesDir(null);
        File file = new File(externalDir, name);
        try {
            StringBuilder sb = new StringBuilder();
            FileInputStream inputStream = new FileInputStream(file);
            int charr;
            while ((charr = inputStream.read()) != -1) {
                sb.append((char)charr);
            }
            inputStream.close();
            return sb.toString();