[英]How to detect when the Battery's low : 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.xml
注冊您的接收器,但請確保您正在過濾的操作是
android.intent.action.BATTERY_LOW
並不是
android.intent.action.ACTION_BATTERY_LOW
(您在代碼中使用過)。
在代碼中注冊您的接收器,而不是在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);
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 的回答投了贊成票 :-)
使用上下文 register 進行注冊。 如果您的目標是 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模擬器不應該處於充電狀態
也許模擬器不響應BATTERY_LOW
和BATTERY_OKAY
消息。 在真正的 Android 設備上嘗試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.