当设备的电池电量低时,我想关闭我的应用程序.
我在清单中添加了以下代码.
我在清单中添加了以下代码.
<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!!"); } }
我正在运行emulater上的应用程序,并使用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
或者用空接收器收听电池电量.
Intent BATTERYintent = this.registerReceiver(null,new IntentFilter( Intent.ACTION_BATTERY_CHANGED)); int level = BATTERYintent.getIntExtra(BatteryManager.EXTRA_LEVEL,-1); Log.v(null,"LEVEL" + level);