Android平臺SDCARD格式化

想了好多天 沒想明白到底怎麼弄,昨天 一朋友告訴我用aidl 試了下,還真的成功了!!
下面我們來看看到底怎麼實現的吧
  因爲google並沒有給我們暴露卸載sdcard和格式化sdcard的api 
  那要怎麼才能實現呢,android中的設置裏可以 卸載和格式化sdcard,那我就來到了settings的源代碼裏找(Settings源代碼要自己下載),
在com.android.settings.deviceinfo中的Memory.java中可以看到OnCreateDialog的方法裏面有個doUnmount(boolean force)方法
來到doUnmount()方法中我看到了
IMountService mountService = getMountService();
        String extStoragePath = Environment.getExternalStorageDirectory().toString();
mountService.unmountVolume(extStoragePath, force);
getMountService()方法中 有
IBinder service = ServiceManager.getService("mount");
           if (service != null) {
               mMountService = IMountService.Stub.asInterface(service);
}
哦 知道了  會寫了 
Method method = Class.forName("android.os.ServiceManager").getMethod("getService", String.class);//利用反射得到ServiceManager類中的getService方法 
IBinder binder = (IBinder) method.invoke(null, "mount");
IMountService iMountService = IMountService.Stub.asInterface(binder);
iMountService.unmountVolume(sDStateString, true);//卸載sdcard


SystemClock.sleep(4000);


iMountService.formatVolume(sDStateString);//格式化sdcard 在沒有卸載掉sdcard時 好像是不能格式化sdcard的 (沒試過!!)
以上代碼會出現異常 記得處理哦!!!








差點忘了,還要在Manifest.xml中加權限
<!-- 格式化SD卡 -->
<uses-permission android:name="android.permission.MOUNT_FORMAT_FILESYSTEMS"/>
在android.os.storage包下加入 以下三個類
還有要加入這IMountService.aidl IMountServiceListener.aidlIMountShutdownObserver.aidl
三個文件
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章