运用反射格式化SD卡

来源:互联网 发布:嫌疑人影评知乎 编辑:程序博客网 时间:2024/05/01 20:17
前些日子要求做格式化SD卡,没办法找了很多都不行,后来找到一个大概的,但是忘记了是哪,所以忘记出处在哪了
这里我的SD卡的路径是因为内部做了swap,交换了内置SD卡 和外置SD卡的路径,所以我写死了
格式化SD卡(运用反射调用隐藏方法)
public int formatSDCard() {
try {
int count=0;
Method getService = Class.forName("android.os.ServiceManager").getMethod("getService", String.class);
Object service = getService.invoke(null, "mount");
Class Stub = Class.forName("android.os.storage.IMountService$Stub");
Method asInterface = Stub.getMethod("asInterface", Class.forName("android.os.IBinder"));
Object mountServ = asInterface.invoke(null, service);
//卸载SD卡
Method unmountVolume = mountServ.getClass().getMethod("unmountVolume", String.class, boolean.class, boolean.class);
unmountVolume.invoke(mountServ, "/storage/sdcard0", true, true);
while (Environment.isExternalStorageRemovable()&&count<30) {
Log.i("TAG", "SD卡还未被完全卸载");
SystemClock.sleep(1000);
count++;
}
//格式化SD卡,返回结果为0则成功,否则失败
Method formatVolume = mountServ.getClass().getMethod("formatVolume", String.class);
Object ob = formatVolume.invoke(mountServ, "/storage/sdcard1");
Log.i("Tag", " m格式化结果 = " + ob);
SystemClock.sleep(2000);
if (ob != null && (Integer)ob == 0) {
Method mountVolume = mountServ.getClass().getMethod("mountVolume", String.class);
Object om = mountVolume.invoke(mountServ, "/storage/sdcard1");
Log.i("Tag", "m挂载结果SD卡= " + om);
if (om != null && (Integer)om == 0) {
return 0;
}
}
} catch (InvocationTargetException e) {
Log.i("TAG", "此处接收被调用方法内部未被捕获的异常");
Throwable t = e.getTargetException();// 获取目标异常
t.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return -1;
}
原创粉丝点击