方法调用由 USB 设备 umount/eject 组成,但它会在以下位置引发异常:
Class.forName("android.os.storage.IMountService")
作为
类未找到异常
我如何进入IMountService
课堂?
fun getRemovabeStorages(context: Context): List<File?>? {
var storages: ArrayList<File>
storages = ArrayList()
val getService: Method = Class.forName("android.os.ServiceManager")
.getDeclaredMethod("getService", String::class.java)
if (!getService.isAccessible) getService.isAccessible = true
val service = getService.invoke(null, "mount") as IBinder
val asInterface: Method = Class.forName("android.os.storage.IMountService")
.getDeclaredMethod("asInterface", IBinder::class.java)
if (!asInterface.isAccessible) asInterface.isAccessible = true
val mountService: Any = asInterface.invoke(null, service)
var storageVolumes: Array<Any>
storageVolumes = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val packageName = context.packageName
val uid =
context.packageManager.getPackageInfo(packageName, 0).applicationInfo.uid
val getVolumeList: Method = mountService.javaClass.getDeclaredMethod(
"getVolumeList",
Int::class.javaPrimitiveType,
String::class.java,
Int::class.javaPrimitiveType
)
if (!getVolumeList.isAccessible) getVolumeList.isAccessible = true
getVolumeList.invoke(mountService, uid, packageName, 0) as Array<Any>
} else {
val getVolumeList: Method = mountService.javaClass.getDeclaredMethod("getVolumeList")
if (!getVolumeList.isAccessible) getVolumeList.isAccessible = true
getVolumeList.invoke(mountService) as Array<Any>
}
for (storageVolume in storageVolumes) {
val cls: Class<*> = storageVolume.javaClass
val isRemovable: Method = cls.getDeclaredMethod("isRemovable")
if (!isRemovable.isAccessible) isRemovable.isAccessible = true
if (isRemovable.invoke(storageVolume) as Boolean) {
val getState: Method = cls.getDeclaredMethod("getState")
if (!getState.isAccessible) getState.isAccessible = true
val state = getState.invoke(storageVolume) as String
if (state == "mounted") {
val getPath: Method = cls.getDeclaredMethod("getPath")
if (!getPath.isAccessible) getPath.isAccessible = true
val path = getPath.invoke(storageVolume) as String
storages.add(File(path))
}
}
}
if (storages != null) {
storages.forEach {
Log.d("JioSettings", "storage-${it.absolutePath}")
val unmountVolume: Method = mountService.javaClass.getDeclaredMethod(
"unmountVolume",
String::class.java,
Boolean::class.javaPrimitiveType,
Boolean::class.javaPrimitiveType
)
if (!unmountVolume.isAccessible) unmountVolume.isAccessible = true
unmountVolume.invoke(mountService, it.absolutePath, true, true)
}
}
return storages
}