简体   繁体   中英

how to detect device connect on android?

I want to detect my connected device using an app on android.

I want to detect a keyboard, mouse, and flash drive.

I am currently using the hwinfo command and 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);
          }

This source code detects the keyboard just fine. But it executes every 4 second.

I want to not use a Timer when I connect a keyboard, mouse, and flash drive.

Detect devices connected on android.

Event detect, or receiver.

How to not use Timer for detecting devices connected on android?

I am going to illustrate USB device detection code. Hope, it will help you.

Step 1 : To ask for permission to access the USB port, which is done in our manifest file like:

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

Step 2 : USB configuration in the Manifest file

<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>  

Step 3 : Create file under res/xml and name it device_filter

paste below code in it :

<?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> 

Step 4 : Security and user permission to connect to a USB device

Since our App does not know if the user has already granted permission, we need to check the user permission flag always, every time that we want to start a USB connection:

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   
   }
 }
}

That's it!! Happy Coding :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM