9

我希望能够检测设备是否已插入。我希望能够以与我们对连接状态相同的方式进行查询。这是可能的还是我需要创建一个监听电池事件的广播接收器?

4

1 回答 1

23

显然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);
}
于 2011-06-02T17:23:38.447 回答