如何在android上检测设备连接?

时间:2017-02-13 01:15:18

标签: android

我想使用Android上的应用程序检测我连接的设备。

我想检测键盘,鼠标和闪存驱动器。

我目前正在使用hwinfo命令和Timer

//keyboard detect class.
public class detectService extends Service {

    static Process hwinfo;
    static String keyboard = "";
    private Handler handler;
    private Timer timer;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
       super.onCreate();
       handler = new Handler();

       TimerTask timerTask = new TimerTask() {
           @Override
           public void run() {
               handler.post(new Runnable() {
                   public void run() {
                       String[] cmd = new String[] {"su", "-c", "hwinfo --keyboard | grep - i 'keyboard'"};
                       try {
                            hwinfo = Runtime.getRuntime().exec(cmd);

                            BufferedReader br = new BufferedReader(new InputStreamReader(hwinfo.getInputStream()));
                            String line;

                            while ((line = br.readLine()) != null) {
                               line = line.trim().toLowerCase();

                               keyboard = line;
                               break;
                            }
                        } catch (IOException e) {
                             e.printStackTrace();
                        }
                        if (keyboard.contains("keyboard")) {
                            timer.cancel();
                            Intent intent = new Intent(this, keyboardDialog.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }
                     }
                  });
                }
             };
             timer = new Timer("Service");
             timer.scheduleAtFixedRate(timerTask, 0 , 4000);
          }

此源代码检测到键盘就好了。 但它每4秒执行一次。

我想在连接键盘,鼠标和闪存驱动器时不使用计时器。

检测Android上连接的设备。

事件检测或接收器。

如何不使用Timer来检测Android上连接的设备?

1 个答案:

答案 0 :(得分:1)

我将说明USB设备检测代码。希望,它会帮助你。

步骤1:要求获得访问USB端口的权限,这在我们的清单文件中完成,如:

<uses-feature android:name="android.hardware.usb.host" />  

第2步:清单文件中的 USB配置

<activity  
android:name="yourPackageName.MainActivity"
android:label="@string/app_name"
android:launchMode="singleInstance">
<intent-filter>
  <action android:name="android.intent.action.MAIN" />
  <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
     <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
<intent-filter>
     <action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" />
</intent-filter>
<meta-data  android:name=
    "android.hardware.usb.action.USB_DEVICE_ATTACHED"
            android:resource="@xml/device_filter" />    
<meta-data android:name=
    "android.hardware.usb.action.USB_DEVICE_DETACHED"
            android:resource="@xml/device_filter" />
</activity>  

第3步:在res / xml下创建文件并将其命名为device_filter

将代码粘贴到其中:

<?xml version="1.0" encoding="utf-8"?>  
<resources>  
<!-- 0x0403 / 0x6001: FTDI FT232R UART -->
<usb-device vendor-id="1027" product-id="24577" />
<!-- 0x2341 / Arduino -->
<usb-device vendor-id="9025" />
</resources> 

第4步:连接USB设备的安全性和用户权限

由于我们的应用程序不知道用户是否已经授予权限,因此每次我们要启动USB连接时,我们都需要始终检查用户权限标志:

void checkUSB(){  
  UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
  // Get the list of attached devices
  HashMap<String, UsbDevice> devices = manager.getDeviceList();                
  // Iterate over all devices
  Iterator<String> it = devices.keySet().iterator();
  while (it.hasNext()) {
   String deviceName = it.next();
   UsbDevice device = devices.get(deviceName);
   String VID = Integer.toHexString(device.getVendorId()).toUpperCase();
   String PID = Integer.toHexString(device.getProductId()).toUpperCase();
    if (!manager.hasPermission(device)) {
      private static final String ACTION_USB_PERMISSION  = "yourPackageName.USB_PERMISSION"; 
   PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
   manager.requestPermission(device, mPermissionIntent);
   return;
} else {
   ... //user permission already granted; prceed to access USB device   
   }
 }
}

那就是!! 快乐编码: - )