Android mount/unmount SD卡

阅读更多

Android SD 卡的內容需要刷新才能讀取(從其它地方copy[PC或內部存儲])

使用mount/unmount的方法
代碼如下:

private void mountUnmountSD(boolean mMount) {
        StorageManager mStorageManager;
        mStorageManager = getApplicationContext().getSystemService(StorageManager.class);
        final List volumes = mStorageManager.getVolumes();
        for (VolumeInfo vol : volumes) {
            if (vol.getType() == VolumeInfo.TYPE_PUBLIC) {
                if(!mMount && vol.getState() == VolumeInfo.STATE_MOUNTED)
                    new UnmountTask(getApplicationContext(), vol).execute();
                if(mMount && vol.getState() == VolumeInfo.STATE_UNMOUNTED) {
                    new MountTask(getApplicationContext(), vol).execute();
                }
            }
        }
    }

    public static class MountTask extends AsyncTask {
        private final Context mContext;
        private final StorageManager mStorageManager;
        private final String mVolumeId;
        public MountTask(Context context, VolumeInfo volume) {
            mContext = context.getApplicationContext();
            mStorageManager = mContext.getSystemService(StorageManager.class);
            mVolumeId = volume.getId();
        }

        @Override
        protected Exception doInBackground(Void... params) {
            try {
                mStorageManager.mount(mVolumeId);
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Exception e) {

        }

    }

    public static class UnmountTask extends AsyncTask {
        private final Context mContext;
        private final StorageManager mStorageManager;
        private final String mVolumeId;
        private final String mDescription;

        public UnmountTask(Context context, VolumeInfo volume) {
            mContext = context.getApplicationContext();
            mStorageManager = mContext.getSystemService(StorageManager.class);
            mVolumeId = volume.getId();
            mDescription = mStorageManager.getBestVolumeDescription(volume);
        }

        @Override
        protected Exception doInBackground(Void... params) {
            try {
                mStorageManager.unmount(mVolumeId);
                return null;
            } catch (Exception e) {
                return e;
            }
        }

        @Override
        protected void onPostExecute(Exception e) {

        }
    }

 

你可能感兴趣的:(Android mount/unmount SD卡)