Android: OTG+USB读取数据

需求:

* 通过otg线使手机连接u盘,并获取到u盘的文件信息

  • manifest注册权限


    
    
    

    
    
  • mainfest 静态注册页面,在mainactivity中配置属性

       
            
                
            
            
      
        
            
                

                

        
        
  • onCreat中注册广播

        IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        registerReceiver(mUsbReceiver, filter);
        discoverDevice();

广播:

      private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTION_USB_PERMISSION://接受到自定义广播
                    synchronized (this) {
                        UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                        if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) { //允许权限申请
                            if (usbDevice != null) {
                              //Do something
                                setupDevice();
                            }
                        } else {
                            Toast.makeText(context, "用户未授权,读取失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                case UsbManager.ACTION_USB_DEVICE_ATTACHED://接收到存储设备插入广播
                    UsbDevice device_add = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (device_add != null) {
                        Toast.makeText(context, "接收到存储设备插入广播", Toast.LENGTH_SHORT).show();
                        discoverDevice();
                    }
                    break;
                case UsbManager.ACTION_USB_DEVICE_DETACHED://接收到存储设备拔出广播
                    UsbDevice device_remove = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (device_remove != null) {
                        Toast.makeText(context, "接收到存储设备拔出广播", Toast.LENGTH_SHORT).show();

                        discoverDevice();
                    }
                    break;
            }
        }
    };
  • 发现设备

      private void discoverDevice() {
        UsbManager usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        massStorageDevices = UsbMassStorageDevice.getMassStorageDevices(this);

        if (massStorageDevices.length == 0) {
            Log.w(TAG, "no device found!");

            Toast.makeText(MainActivity.this, "没有设备",Toast.LENGTH_SHORT).show();
          listView.setAdapter(null);
            return;
        }
        currentDevice = 0;

        UsbDevice usbDevice = (UsbDevice) getIntent().getParcelableExtra(UsbManager.EXTRA_DEVICE);

        if (usbDevice != null && usbManager.hasPermission(usbDevice)) {
            Log.d(TAG, "received usb device via intent");
            // requesting permission is not needed in this case

            Toast.makeText(MainActivity.this, "接受到usb",Toast.LENGTH_SHORT).show();
            setupDevice();
        } else {
            // first request permission from user to communicate with the
            // underlying
            // UsbDevice
            Toast.makeText(MainActivity.this, "usbDevice==nil",Toast.LENGTH_SHORT).show();
            PendingIntent permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(
                    ACTION_USB_PERMISSION), 0);
            usbManager.requestPermission(massStorageDevices[currentDevice].getUsbDevice(), permissionIntent);
        }
    }
  • 读取设备信息

  private void setupDevice() {
        try {
            massStorageDevices[currentDevice].init();

            // we always use the first partition of the device
            currentFs = massStorageDevices[currentDevice].getPartitions().get(0).getFileSystem();
            Log.d(TAG, "Capacity: " + currentFs.getCapacity());
            Log.d(TAG, "Occupied Space: " + currentFs.getOccupiedSpace());
            Log.d(TAG, "Free Space: " + currentFs.getFreeSpace());
            Log.d(TAG, "Chunk size: " + currentFs.getChunkSize());
            Toast.makeText(MainActivity.this, "设备目录"+currentFs.getRootDirectory(),Toast.LENGTH_SHORT).show();
            UsbFile root = currentFs.getRootDirectory();

            adapter = new UsbFileListAdapter(this, root);
            listView.setAdapter(adapter);
        } catch (IOException e) {
            Log.e(TAG, "error setting up device", e);
            Toast.makeText(MainActivity.this, "错误",Toast.LENGTH_SHORT).show();
        }

    }

注意:

1、使用的开源的:compile 'com.github.mjdev:libaums:0.5.3'
2、fs的支持:compile 'com.github.magnusja:java-fs:+'
需要配置:
java classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3' classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'


  • 由于本人是从事的iOS的开发,这个只是临时的一个小任务,所以没有深入了解,后续继续深入的话会继续写下去的!

下一节:android读取单反的数据

你可能感兴趣的:(Android: OTG+USB读取数据)