![](/img/trans.png)
[英]How to restrict user to connect USB when my Android app is running?
[英]How to stop my Android app with a warning when the user has USB Connected the storage to the PC
我的應用程序需要用戶手機USB存儲器或SD卡中的某些文件,當它們將大容量存儲器連接到PC進行文件傳輸時,我的應用程序崩潰了。
我想檢查USB是否以文件傳輸模式連接,如果要連接USB,請停止我的應用程序並顯示帶有警告的Toast,這與本機相機應用程序相同。
我讀了很多關於這個主題的文章,有各種各樣的解決方案,所有的解決方案都是半有效的
public static boolean isUSBConnected(Context context) {
Intent usbCheck = context.registerReceiver(null, new IntentFilter("android.hardware.usb.action.USB_STATE"));
return usbCheck.getExtras().getBoolean("connected");
}
if (isUSBConnected(this)) {
toastMaker.toast(MainActivity.this, "Warning message", Toast.LENGTH_SHORT);
finish();
}
但是即使在沒有打開文件傳輸模式的情況下將USB電纜插入設備也可以使用。
可能您可以嘗試這樣做,以檢查存儲空間是否可用和/或可寫,
private static boolean isExternalStorageReadOnly() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
}
return false;
}
private static boolean isExternalStorageAvailable() {
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
return true;
}
return false;
}
另外,您應該嘗試/捕獲所有讀/寫操作,這里有所有示例: http : //www.mysamplecode.com/2012/06/android-internal-external-storage.html
廣播接收器被系統吞沒了,所以我無法使用內部廣播監視器(從Google Play安裝)來接聽。
唯一真正的解決方案是查看未找到文件觸發了什么錯誤,然后捕獲該io錯誤以確保正確處理了該錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.