Android 利用广播监听usb连接状态(变化情况)

废话不多说了,直接给大家贴代码了,具体代码如下所示:

package com.lgs.test.testcode.receiver; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.widget.Toast; 
/** 
 * Created by Administrator on 2017/6/26. 
 */ 
public class UsbConnect { 
  private final static String ACTION = "android.hardware.usb.action.USB_STATE"; 
  public void start(Context context) { 
    IntentFilter filter = new IntentFilter(); 
    filter.addAction(ACTION); 
    context.registerReceiver(usBroadcastReceiver, filter); 
  } 
  BroadcastReceiver usBroadcastReceiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
      String action = intent.getAction(); 
      Toast.makeText(context, "aciton =" + action, Toast.LENGTH_SHORT).show(); 
      if (action.equals(ACTION)) { 
        boolean connected = intent.getExtras().getBoolean("connected"); 
        Toast.makeText(context, "aciton =" + connected, Toast.LENGTH_SHORT).show(); 
        if (connected) { 
        } else { 
        } 
      } 
    } 
  }; 
} 

以上所述是小编给大家介绍的Android 利用广播监听usb连接状态,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

你可能感兴趣的:(Android 利用广播监听usb连接状态(变化情况))