开发者

Keep widget BroadcastReceiver alive even if not instantiated from Manifest

开发者 https://www.devze.com 2023-01-27 23:04 出处:网络
i have a widget which needs to listen to BATTERY_CHANGED event, however, since this event is protected and cannot be declared from the manifest i create a new Broadc开发者_如何学PythonastReceiver from

i have a widget which needs to listen to BATTERY_CHANGED event, however, since this event is protected and cannot be declared from the manifest i create a new Broadc开发者_如何学PythonastReceiver from the Application constructor:

public void onCreate() {
    super.onCreate();
    if (DEBUG) Log.d(TAG, "onCreate()");
    // Register receivers        
    if (receiver == null) {
        receiver = new MYReceiver(this);
    }
    // Create new intentfilter
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
    registerReceiver(receiver, intentFilter);
}

Then, from the Receiver i call a static method of the AppWidgetProvider which actually update the widget using RemoteViews. Everything works flawlessy until 1 hour as passed, after that time my Receiver disappears and the widget does not update anymore. I'm testing this on a Droid with 2.2.1 firmware-

What i'm doing wrong? Is this the correct way to update the widget (i just need that event so i don't want to have a service if its not needed). Should i use an AlarmManager to be sure from time to time that my receiver is still there? I can i do this?

Thanks.


I don't have a clue why your receiver got lost after an hour but what about using the AlarmManager to check periodically if it is still there? So you can re-register it if it got lost.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号