我希望能够检测设备是否已插入.我希望能够以与连接状态相同的方式查询.这是可能的还是我需要创建一个侦听电池事件的广播接收器?
解决方法
显然,ACTION_BATTERY_CHANGED是一个“粘性广播”,这意味着你可以在广播后随时注册并接收它.要获得插入状态,您可以执行以下操作:
public void onCreate() { BroadcastReceiver receiver = new BroadcastReceiver() { public void onReceive(Context context,Intent intent) { int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED,-1); if (plugged == BatteryManager.BATTERY_PLUGGED_AC) { // on AC power } else if (plugged == BatteryManager.BATTERY_PLUGGED_USB) { // on USB power } else if (plugged == 0) { // on battery power } else { // intent didnt include extra info } } }; IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); registerReceiver(receiver,filter); }