2016-07-14 73 views
0

我一直在試聽Battery BroadCast事件。插入/拔出。電池廣播不發送任何狀態代碼

public class BatteryReceiver extends BroadcastReceiver { 
    public BatteryReceiver() { 
    } 

    @Override 
    public void onReceive(Context context, Intent intent) { 

     int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1); 

     if(status == BatteryManager.BATTERY_STATUS_CHARGING){ 
      Toast.makeText(context, "Charging", Toast.LENGTH_SHORT).show(); 
     } else if(status == BatteryManager.BATTERY_STATUS_DISCHARGING || status == BatteryManager.BATTERY_STATUS_NOT_CHARGING){ 
      Toast.makeText(context, "Not charging", Toast.LENGTH_SHORT).show(); 
     } 
    } 
} 

我已經加入清單的行動:

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

回答

0

如果你想,當插入/拔出而已,我想你可以檢查收到的意向進行跟蹤。

public class BatteryReceiver extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 

     if(intent != null) { 
      String action = intent.getAction(); 
      if(action != null) { 
       if(action.equals("android.intent.action.ACTION_POWER_CONNECTED"){ 
        Toast.makeText(context, "Charging", Toast.LENGTH_SHORT).show(); 
       } else if(action.equals("android.intent.action.ACTION_POWER_DISCONNECTED"){ 
        Toast.makeText(context, "Not charging", Toast.LENGTH_SHORT).show(); 
       } 
      } 
     } 
    } 
} 

UPDATE

但如果你真的要檢查電池充電時,你必須改變你的代碼。

首先,我注意到,當您註冊BroadcastReceiver通過AndroidManifest.xml,意圖獲得沒有任何多餘的(在日誌中,當您打印的意圖它會出現hasExtras:

Intent { act=android.intent.action.ACTION_POWER_DISCONNECTED flg=0x4000010 cmp=com.pivoto.myapplication/.BootCompletedReceiver } 
Intent { act=android.intent.action.ACTION_POWER_CONNECTED flg=0x4000010 cmp=com.pivoto.myapplication/.BootCompletedReceiver } 

然後,我搜查StackOverflow的我發現這個ANSWER(請,檢查它的更多細節):

那麼,有沒有一種方法來「請求」當你想要的電池狀態:

public class BootCompletedReceiver extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     if(intent != null) { 
      Intent oneTimeOnlyBatteryIntent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); 
      int status = -1; 
      if(oneTimeOnlyBatteryIntent != null) 
       status = oneTimeOnlyBatteryIntent.getIntExtra(BatteryManager.EXTRA_STATUS, -1); 
      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(); 
      } 
     } 
    } 
} 
+0

第一個會爲我工作感謝,歡呼!但第二個總是返回-1 –

+0

@GurleenSethi我更新了答案..現在,它正在工作 – W0rmH0le

+0

@GurleenSethi您測試了更新的答案嗎?如果可能的話,讓我知道結果!謝謝 – W0rmH0le