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
三个文件
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章