Android中查看USB连接的外接设备信息的代码实例

2019-12-10 20:06:33于丽
易采站长站为您分析Android中查看USB连接的外接设备信息的代码实例,需要的朋友可以参考下    

1,USB存储设备(如:U盘,移动硬盘):

 //USB存储设备 插拔监听与 SD卡插拔监听一致。

复制代码
 private USBBroadCastReceiver mBroadcastReceiver;

 

     IntentFilter iFilter = new IntentFilter();
       iFilter.addAction(Intent.ACTION_MEDIA_EJECT);
       iFilter.addAction(Intent.ACTION_MEDIA_MOUNTED);
       iFilter.addAction(Intent.ACTION_MEDIA_REMOVED);
       iFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);

       iFilter.addDataScheme("file");
       mBroadcastReceiver = new USBBroadCastReceiver();
       registerReceiver(mBroadcastReceiver, iFilter);

private class USBBroadCastReceiver extends BroadcastReceiver {
      @Override
      public void onReceive(Context context, Intent intent) {
       String action = intent.getAction();

       if (action.equals(Intent.ACTION_MEDIA_EJECT)) {

          //USB设备移除,更新UI     
       } else if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {

          //USB设备挂载,更新UI
        }
      }
 }

  //获得挂载的USB设备的存储空间使用情况

public static String getUSBStorage(Context context){
      // USB Storage 

      //storage/udisk为USB设备在Android设备上的挂载路径.不同厂商的Android设备路径不同。

      //这样写同样适合于SD卡挂载。
      File path = new File("/storage/udisk");

      StatFs stat = new StatFs(path.getPath());