【问题标题】:how to detect device connect on android?如何在android上检测设备连接?
【发布时间】:2019-01-24 15:25:39
【问题描述】:

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

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

我目前正在使用hwinfo 命令和定时器

//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 上连接的设备?

【问题讨论】:

    标签: android


    【解决方案1】:

    我将说明 USB 设备检测代码。希望对你有所帮助。

    第 1 步:请求访问 USB 端口的权限,这在我们的清单文件中完成,例如:

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

    第 2 步:Manifest 文件中的 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   
       }
     }
    }
    

    就是这样!! 快乐编码:-)

    【讨论】:

    猜你喜欢
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 2013-11-10
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多