0

I've written a battery monitor widget that I can update when the screen is turned on using a background Service with BroadcastReceivers and an Alarm. I can also stop updating when the screen is turned off. However, the Service only runs until the system stops the background service.

  1. I don't want to use a foreground service because the user does not need to be notified.
  2. Always checking and restarting the background service does not seem like a good solution.
  3. I don't think I can bind a service to a widget. But, I'm new to this and still learning.

How do I get around this problem? I started looking into WorkManager but haven't found what I'm looking for.

Any suggestions to point me in the right direction would be much appreciated.

amm811
  • 1
  • 2

1 Answers1

2

You could create a listener class to listen for android lock screen and unlock events,use broadcast to receive the state of screen.

 private class ScreenBroadcastReceiver : BroadcastReceiver
{
private String action = null;

    public override void OnReceive(Context context, Intent intent)
    {
        action = intent.Action;
        if (Intent.ActionScreenOn == action)
        { // screen on
            mScreenStateListener.onScreenOn();
        }
        else if (Intent.ActionScreenOff == action)
        { // screen off
            mScreenStateListener.onScreenOff();
        }
        else if (Intent.ActionUserPresent == action)
        { // unlock
            mScreenStateListener.onUserPresent();
        }
    }
}

For more code for the listener, you could refer to the link below. https://stackoverflow.com/a/55014763/11850033

You could override the OnUpdate of AppWidgetProvider. And then trigger an onUpdate on your Widget. How to call onUpdate method of widget on button click?

Update:

You could try to inprove the level of context.

 mContext.ApplicationContext.RegisterReceiver(mScreenReceiver, filter);
Wendy Zang - MSFT
  • 10,509
  • 1
  • 7
  • 17