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

Ada*_*H S 12 java 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>
Run Code Online (Sandbox Code Playgroud)

并在接收器中的代码

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!!");
    }
}
Run Code Online (Sandbox Code Playgroud)

我在emulater上运行应用程序并使用telnet更改电池电量.它会改变电池电量但不显示任何烤面包或日志.

我错过了什么?任何帮助表示赞赏!谢谢.

小智 40

您可以在中注册接收器AndroidManifest.xml,但请确保您要过滤的操作是

android.intent.action.BATTERY_LOW

并不是

android.intent.action.ACTION_BATTERY_LOW

(您在代码中使用过的).


EZD*_*sIt 7

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的回答:-)


Yah*_*r10 6

在代码中注册您的接收器,而不是在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
Run Code Online (Sandbox Code Playgroud)

或者用空接收器听电池电量.

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