Is there any way to know(programmatically) in your Activity/Application that the user has connected your phone to PC through USB?
This works for me.
Add this on your AndroidManifest.xml
And Create your BroadcastReceiver.
public class PlugInControlReceiver extends BroadcastReceiver {
@Override public void onReceive(final Context context, Intent intent) {
String action = intent.getAction();
Log.v("PlugInControlReceiver","action: "+action);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
if(action.equals("android.hardware.usb.action.USB_STATE")) {
if(intent.getExtras().getBoolean("connected")){
Toast.makeText(context, "USB Connected", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "USB Disconnected", Toast.LENGTH_SHORT).show();
}
}
} else {
if(action.equals(Intent.ACTION_POWER_CONNECTED)) {
Toast.makeText(context, "USB Connected", Toast.LENGTH_SHORT).show();
}
else if(action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
Toast.makeText(context, "USB Disconnected", Toast.LENGTH_SHORT).show();
}
}
}
}