如何检测何时电池电量低:Android?


问题内容

当设备的电池电量不足时,我想关闭我的应用程序。我在清单中添加了以下代码。

 <receiver android:name=".BatteryLevelReceiver" 
         <intent-filter>
            <action android:name="android.intent.action.ACTION_BATTERY_LOW" />
            <action android:name="android.intent.action.ACTION_BATTERY_OKAY" />
        </intent-filter>
 </receiver>

并在接收器中遵循以下代码

public class BatteryLevelReceiver extends BroadcastReceiver 
{

    @Override
    public void onReceive(Context context, Intent intent) 
    {
        Toast.makeText(context, "BAttery's dying!!", Toast.LENGTH_LONG).show();
        Log.e("", "BATTERY LOW!!");
    }
}

我正在模拟器上运行该应用程序,并使用telnet更改了电池电量。它会更改电池电量,但不会显示任何吐司或记录。

我想念什么?任何帮助表示赞赏!谢谢。


问题答案:

在代码中而不是在AndroidManifest文件中注册您的接收器。

registerReceiver(batteryChangeReceiver, new IntentFilter(
    Intent.ACTION_BATTERY_CHANGED)); // register in activity or service

public class BatteryChangeReceiver extends BroadcastReceiver {

    int scale = -1;
    int level = -1;
    int voltage = -1;
    int temp = -1;

    @Override
    public void onReceive(Context context, Intent intent) {
        level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
        voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);
    }
}

unregisterReceiver(batteryChangeReceiver);//unregister in the activity or service

或使用null接收器收听电池电量。

Intent BATTERYintent = this.registerReceiver(null, new IntentFilter(
        Intent.ACTION_BATTERY_CHANGED));
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
Log.v(null, "LEVEL" + level);