2012-07-22 167 views
5
@Override 
public void onReceive(Context context, Intent intent) { 
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, 
    BatteryManager.BATTERY_STATUS_UNKNOWN); 

    if (status == BatteryManager.BATTERY_STATUS_CHARGING 
     || status == BatteryManager.BATTERY_STATUS_FULL) 
     Toast.makeText(context, "Charging!", Toast.LENGTH_SHORT).show(); 
    else 
     Toast.makeText(context, "Not Charging!", Toast.LENGTH_SHORT).show(); 
} 

清單:電池狀態始終不充電

<receiver android:name=".receiver.BatteryReceiver"> 
    <intent-filter> 
     <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/> 
     <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/> 
     <action android:name="android.intent.action.BATTERY_CHANGED" /> 
    </intent-filter> 
</receiver> 

在這段代碼,麪包總是顯示 「不在充電!」。我在一臺實際的設備上測試過,當我插入交流電或USB電源時,它仍然顯示「不充電!」吐司。

+0

那裏有什麼問題你intent.getIntExtra,檢查其中這些方法正在被呼叫,並確保你正在設置意圖的正確參數 – John 2012-07-22 18:24:22

+0

你的地位是什麼? – zmbq 2012-07-22 18:24:53

+0

@John我在清單中使用它。 – 2012-07-22 18:28:48

回答

6

您無法通過清單註冊ACTION_BATTERY_CHANGED,因此您沒有收到這些廣播。您正在嘗試從Intents獲得BatteryManager臨時演員中沒有這些演員的演員(例如,ACTION_POWER_CONNECTED)。因此,您將獲得默認值BATTERY_STATUS_UNKNOWN

+0

那麼我將如何註冊它編程? – 2012-07-22 18:33:34

+0

@MohitDeshpande:調用'registerReceiver()',就像您以編程方式註冊任何其他的'BroadcastReceiver'一樣。請參閱:https://github.com/commonsguy/cw-omnibus/tree/master/SystemEvents/OnBattery – CommonsWare 2012-07-22 18:35:59

2

嘗試以下操作:

IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); 
Intent batteryStatus = context.registerReceiver(null, ifilter); 
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1); 

'狀態' 現在是1和5之間的值:

1 = Unknown 
2 = Charging 
3 = Discharging 
4 = Not Charging 
5 = Full 

您的代碼:

if (status == BatteryManager.BATTERY_STATUS_CHARGING 
    || status == BatteryManager.BATTERY_STATUS_FULL) ... 

可以寫成:

if (status == 2 || status == 5) ... 

兩者都是相同的,因爲BatteryManager.BATTERY_STATUS_CHARGING是一個常數,總是等於2,BatteryManager.BATTERY_STATUS_FULL是一個常數,總是等於5

+0

好的答案,但請不要在代碼中使用幻數:http://stackoverflow.com/questions/47882/what -is-A-魔號和 - 爲什麼 - 是 - 它壞 – kellogs 2017-01-20 13:13:49