private PendingIntent mPermissionIntent;
private static TextView tv;
private boolean isconnect=true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=findViewById(R.id.tv);
initUsbAccessoryWidget();//广播注册
}
private void initUsbAccessoryWidget() {
mPermissionIntent = PendingIntent.getBroadcast(this, 0,
new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(Intent.ACTION_BATTERY_CHANGED);
//注册广播
registerReceiver(mUsbReceiver, filter);
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
if (usbCharge) {//USB连接
if (isconnect) {//不重复执行
tv.setText("USB连接");
isconnect = false;
}
} else {
isconnect = true;
tv.setText("USB断开");
}
}
}
};
@Override
protected void onDestroy() {
super.onDestroy();
//停止广播
if (null!=mUsbReceiver ){
unregisterReceiver(mUsbReceiver);
}
}
06-26
2401