Android獲取電池充電狀態的方式

廢話不多說,直接進入正題。

我需要知道當前設備是否在充電,如何實現?

1、註冊電池更改廣播ACTION_BATTERY_CHANGED接收器。實現代碼如下:

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_BATTERY_CHANGED);
        context.registerReceiver(this, filter);
..............


    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
             int status=intent.getIntExtra("status",BatteryManager.BATTERY_STATUS_UNKNOWN);
                if(status==BatteryManager.BATTERY_STATUS_CHARGING) {
                    //DoSomeThing
                }
                else {
                    //DoSomeThing
                }
        }
    }

二、直接註冊充電狀態廣播接收器

        filter = new IntentFilter();
        filter.addAction(BatteryManager.ACTION_CHARGING);
        filter.addAction(BatteryManager.ACTION_DISCHARGING);
        context.registerReceiver(this, filter);
..............


    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        if (action.equals(BatteryManager.ACTION_CHARGING)) {
            //DoSomething
        } else (action.equals(BatteryManager.ACTION_DISCHARGING)) {
            //DoSomething
        }
    }

其實上面兩種方式歸結起來是一種方式。仔細分析一下這個兩個廣播在發送時候,就知道原因了。

frameworks/base/services/core/java/com/android/server/BatteryService.java#sendIntentLocked()

        //  Pack up the values and broadcast them to everyone
        final Intent intent = new Intent(Intent.ACTION_BATTERY_CHANGED);
        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
                | Intent.FLAG_RECEIVER_REPLACE_PENDING);

        int icon = getIconLocked(mBatteryProps.batteryLevel);

        intent.putExtra(BatteryManager.EXTRA_STATUS, mBatteryProps.batteryStatus);//電池狀態信息,可以在廣播中直接獲取當前電池的狀態信息
        intent.putExtra(BatteryManager.EXTRA_HEALTH, mBatteryProps.batteryHealth);
        intent.putExtra(BatteryManager.EXTRA_PRESENT, mBatteryProps.batteryPresent);
        intent.putExtra(BatteryManager.EXTRA_LEVEL, mBatteryProps.batteryLevel);//電量值
        intent.putExtra(BatteryManager.EXTRA_SCALE, BATTERY_SCALE);
        intent.putExtra(BatteryManager.EXTRA_ICON_SMALL, icon);
        intent.putExtra(BatteryManager.EXTRA_PLUGGED, mPlugType);//充電類型
        intent.putExtra(BatteryManager.EXTRA_VOLTAGE, mBatteryProps.batteryVoltage);
        intent.putExtra(BatteryManager.EXTRA_TEMPERATURE, mBatteryProps.batteryTemperature);//電池溫度
        intent.putExtra(BatteryManager.EXTRA_TECHNOLOGY, mBatteryProps.batteryTechnology);
        intent.putExtra(BatteryManager.EXTRA_INVALID_CHARGER, mInvalidCharger);
        intent.putExtra(BatteryManager.EXTRA_MAX_CHARGING_CURRENT, mBatteryProps.maxChargingCurrent);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章