2012-06-30 127 views
11

我与此帖有完全相同的问题:Battery broadcast receiver doesn't work。但似乎没有人回答这个问题。我无法接收电池状态更改的广播?

这里是我的广播接收器:

public class BatteryLevelReceiver extends BroadcastReceiver{ 


    @Override 
    public void onReceive(Context context, Intent intent) { 
    Log.v("plugg", "plug change fired"); 
    Toast.makeText(context, " plug change fired", Toast.LENGTH_LONG).show(); 
     } 

这里是我的AndroidManifest.xml:

<receiver android:name=".ReceversAndServices.BatteryLevelReceiver"> 
       <intent-filter android:priority="900"> 
       <action android:name="android.intent.action.BATTERY_LOW" /> 

       </intent-filter> 
      </receiver> 

      <receiver android:name=".ReceversAndServices.BatteryLevelReceiver"> 
       <intent-filter android:priority="900"> 
       <action android:name="android.intent.action.BATTERY_CHANGED" /> 
       </intent-filter> 
      </receiver> 

我也加入了这一行的清单:

<uses-permission android:name="android.permission.BATTERY_STATS"/> 

但仍没有成功!

我真的很感激,如果有人能告诉我我做错了什么。

回答

19

the documentation for ACTION_BATTERY_CHANGED

您无法通过舱单申报组件收到此,只有通过显式注册它与Context.registerReceiver()。请参阅ACTION_BATTERY_LOW,ACTION_BATTERY_OKAY,ACTION_POWER_CONNECTED和ACTION_POWER_DISCONNECTED以了解与电池相关的不同广播,这些广播可以通过清单接收器发送并发送。

你有它:你必须从你的Java代码明确注册它。

+0

感谢Darshan,但我只想在电池电量不足或插上电源时运行服务。请您告诉我我该怎么做? –

+2

如果这些是你关心的唯一两个事件,那么你根本不需要'ACTION_BATTERY_CHANGED',并且在清单中你将很好地注册它们。被插入的广播是“ACTION_POWER_CONNECTED”。这两个操作都可以在同一个'intent-filter'下,你不需要设置优先级,也不需要'BATTERY_STATS'权限。 –

2

我刚刚遵循Android Developer Guide的Monitoring the Battery Level and Charging State并立即获得成功。如果BatteryLevelReceiver是它自己的类,然后我会建议:

<receiver android:name=".BatteryLevelReceiver"> 
    <intent-filter android:priority="900"> 
     <action android:name="android.intent.action.BATTERY_LOW" /> 
     <action android:name="android.intent.action.BATTERY_CHANGED" /> 
    </intent-filter> 
</receiver> 

加成

我愿意猜测,你写BatteryLevelReceiver在ReceversAndServices嵌套类。根据Receiver as inner class in Android,你不能用非静态类来做到这一点。你可以做BatteryLevelReceiver静态类和登记的onResume()接收器,但是那么你的应用程序将需要运行赶上事件......将您的接收器一个单独的类和注册这些意图:

<receiver android:name=".BatteryLevelReceiver"> 
    <intent-filter android:priority="900"> 
     <action android:name="android.intent.action.BATTERY_LOW" /> 
     <action android:name="android.intent.action.BATTERY_OKAY" /> 
     <action android:name="android.intent.action.ACTION_POWER_CONNECTED" /> 
     <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" /> 
    </intent-filter> 
</receiver> 

(不BATTERY_CHANGED为达山计算指出。)

+3

你必须立即接受成功'BATTERY_LOW',但你永远不会收到'BATTERY_CHANGED'的方式。 –

+0

感谢Sam,但是一旦我给它添加静态代码,我就会得到一个错误:( –

+0

@Kevin_Dingo是的,我猜测你正在尝试做什么,我意识到自己的错误并正在写更新,如果你还在获取错误,请添加更多的细节到您的问题和logcat错误 – Sam