Android: Detecting USB

前端 未结 6 1856
一生所求
一生所求 2020-11-27 06:13

Is there any way to know(programmatically) in your Activity/Application that the user has connected your phone to PC through USB?

6条回答
  •  失恋的感觉
    2020-11-27 06:46

    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();
                }
            }  
       }      
    }
    

提交回复
热议问题