我有一个小部件,当它创建时应该启动广播接收器。 更换电池后,此接收器会处理小部件更新。
这是我的代码:
AppWidgetProvider代码:
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
broadcastReceiver = new BatteryInfo();
IntentFilter mIntentFilter = new IntentFilter();
mIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
context.getApplicationContext().registerReceiver(broadcastReceiver, mIntentFilter);
}
BroadcastReceiver代码
public class BatteryInfo extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
// some actions...
}
}
添加小部件后,此方法可以正常工作。 Widget的onUpdate会被调用,然后当电池状态发生变化时,接收方会继续被调用。
重启设备后问题开始。设备重新启动后,几秒钟后小部件重新初始化,再次调用小部件的onUpdate,然后两次调用接收器,并立即死亡。之后,它会出现在logcat中:
1950-3391/? I/ActivityManager: Process [my process name] (pid 7752) has died: cch+4CEM
1950-2013/? W/BroadcastQueue: Background execution not allowed: receiving Intent { act=android.intent.action.ACTION_POWER_DISCONNECTED flg=0x4000010 (has extras) } to [my process name]/.BatteryInfo
1950-2013/? W/BroadcastQueue: Background execution not allowed: receiving Intent { act=android.intent.action.ACTION_POWER_CONNECTED flg=0x4000010 (has extras) } to [my process name]/.BatteryInfo
为什么在重新启动后重新初始化窗口小部件有什么关系? 只要窗口小部件在屏幕上,我如何确保我的接收器保持活动状态?
答案 0 :(得分:0)
您忘了Unregister
BroadCastReceiver
吗?请检查您的Unregistered
是否broadcastReciever
比您更合适。
答案 1 :(得分:0)
这是预期的。
对设备进行重新设置后,所有侦听器都将被删除,您应该重新注册它们。在这种情况下,您需要收听BOOT_COMPLETE事件以重新注册您的广播。 像这样:
AndroidManifest.xml:
<manifest>
...
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
...
<application>
...
<!-- UPDATE YOUR BatteryInfo RECEIVER WITH the INFO BELOW -->
<receiver
...
android:permission="android.permission.RECEIVE_BOOT_COMPLETED"
android:exported="true">
<intent-filter>
...
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
BatteryInfo.java
public class BatteryInfo extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if("android.intent.action.BOOT_COMPLETED".equals(action) {
Log.v("BatteryInfo", "Boot completed. Registering to battery info events");
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
context.getApplicationContext().registerReceiver(this, intentFilter);
} else if() {
Log.v("BatteryInfo", "Battery event");
// Some Actions
} else {
Log.e("BatteryInfo", "Action not expected: " + action);
}
}
}