如何对特定的BroadcastReceiver意图作出反应

时间:2012-11-01 03:19:41

标签: android android-intent

我正在尝试做基本的接收器并让它在电池状态改变时显示一个干杯,但是当一个改变时,所有其他干杯也会被执行。

我正在使用AVD通过telnet操作电池

public class battery1 extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        String strCharge = null, strHealth = null, strPlug = null;
        int status, health, plugged, temp;

        status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        String action = intent.getAction();

        if (intent.hasExtra(BatteryManager.EXTRA_STATUS)) {
            switch(status) {
            case BatteryManager.BATTERY_STATUS_CHARGING:
                strCharge = "Charging";
                break;
            case BatteryManager.BATTERY_STATUS_DISCHARGING:
                strCharge = "Discharging";
                break;
            case BatteryManager.BATTERY_STATUS_FULL:
                strCharge = "Full";
                break;
            case BatteryManager.BATTERY_STATUS_UNKNOWN:
                strCharge = "Unknown";
                break;
            }

            Toast.makeText(context,"Charging status: " + strCharge, Toast.LENGTH_SHORT).show();
        }

        health = intent.getIntExtra(BatteryManager.EXTRA_HEALTH, -1);
        if (intent.hasExtra(BatteryManager.EXTRA_HEALTH))
        {
            switch (health) {
            case BatteryManager.BATTERY_HEALTH_DEAD:
                strHealth = "Dead";
                break;
            case BatteryManager.BATTERY_HEALTH_GOOD:
                strHealth = "Good";
                break;
            case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
                strHealth = "Over voltage";
                break;
            case BatteryManager.BATTERY_HEALTH_OVERHEAT:
                strHealth = "Overheat";
                break;
            case BatteryManager.BATTERY_HEALTH_UNKNOWN:
                strHealth = "Unknown";
                break;
            }

            Toast.makeText(context,"Battery health is " + strHealth, Toast.LENGTH_SHORT).show();
        }

    }
}

0 个答案:

没有答案