androidandroid-intentusbandroid-serviceandroid-usb

How to detected PC connection from an Android Application?


I'm trying to activate USB tethering when i detect a connexion to a linux PC. I already have found the following intent filter : ACTION_POWER_CONNECTED

Is there a more specific Intent filter to detect data enabled connections ?

If not how can i detect the data connection ?

ACTION_POWER_DISCONNECTED will do the Job to Deactivate the tethering.

Thank you


Solution

  • I don't really understand why but checking the charge state seems to do the job. In the following piece of code usbCharge is false when on simple charger and true where on a computer.

    public void onReceive(final Context context, Intent intent) {
        IntentFilter extraFilterToGetBatteryInfo = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent extraIntentToGetBatteryInfo = context.getApplicationContext().registerReceiver(null, extraFilterToGetBatteryInfo);
    
        int chargePlug = extraIntentToGetBatteryInfo.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
    
        if (usbCharge) {
            // Enable tethering
            Intent tetherSettings = new Intent();
            tetherSettings.setClassName("com.android.settings", "com.android.settings.TetherSettings");
            tetherSettings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(tetherSettings);
        }
    }