">
我想在设备电池电量不足时关闭我的应用程序。我在manifest中添加了以下代码。
<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更改电池电平。它会改变电池电量,但不会显示任何toast或日志。
我遗漏了什么?如有任何帮助,我们不胜感激!
发布于 2012-11-05 09:07:40
在代码中注册接收器,而不是在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);
发布于 2013-05-14 19:20:42
您可以在AndroidManifest.xml
中注册接收器,但请确保您要过滤的操作是
android.intent.action.BATTERY_LOW
而不是
android.intent.action.ACTION_BATTERY_LOW
(您已经在代码中使用了它)。
发布于 2013-08-22 21:29:32
k3v是正确的。
文档中实际上有一个错误。它特别提到要使用android.intent.action.ACTION_BATTERY_LOW
。但是放在清单中的正确操作是android.intent.action.BATTERY_LOW
请看这里:http://developer.android.com/training/monitoring-device-state/battery-monitoring.html
(不能投票给k3v的答案,没有足够的StackOverflow点东西...)
更新:我现在可以而且确实投票支持k3v的答案:-)
https://stackoverflow.com/questions/13228849
复制相似问题