13

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

 <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 更改电池电量。它会更改电池电量,但不显示任何吐司或日志。

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

4

5 回答 5

41

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

android.intent.action.BATTERY_LOW

并不是

android.intent.action.ACTION_BATTERY_LOW

(您在代码中使用过)。

于 2013-05-14T19:20:42.267 回答
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 的回答进行了投票:-)

于 2013-08-22T21:29:31.527 回答
7

在代码中注册您的接收器,而不是在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);
于 2012-11-05T09:07:40.293 回答
1

使用上下文寄存器注册。如果您的目标是 Android 8.0 或更高版本,则不能使用清单声明的接收器。将此代码粘贴到您的主要活动中以进行注册。

 BroadcastReceiver receiver = new BatteryLevelReceiver();
        IntentFilter filter =new IntentFilter(BatteryManager.EXTRA_BATTERY_LOW);
        filter.addAction(Intent.ACTION_BATTERY_LOW);
        this.registerReceiver(receiver, filter);

你很高兴 PS模拟器不应该处于充电状态

于 2019-02-12T19:45:17.000 回答
-1

也许模拟器不响应BATTERY_LOWBATTERY_OKAY消息。在真正的 Android 设备上试用。

于 2015-09-23T13:30:58.330 回答