Search code examples
androidandroid-appwidgetlockscreenwakelockappwidgetprovider

Android Lock Screen App Widget: how to wake up the device (and send it back to sleep again after)


Hi and thanks for your help.

I have the following situation.

I have a Lock Screen Widget, when the user taps it the App Widget perform some tasks (updates itself).

The point is that: if the phone is in sleep mode and the user taps the App Widget, the App Widget would update itself, but the App Widget itself is not visible.

Therefore I need to wake up the device when the user taps the Lock Screen Widget - and after it can go to sleep again :-) -

Therefore I could use:

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK|PowerManager.ACQUIRE_CAUSES_WAKEUP, "bbbb");
wl.acquire();

In the AppWidgetProvider. The point is: how do I call "release()" so that the device can go back to sleep?

If I do:

    PowerManager pm = (PowerManager) ctxt.getSystemService(Context.POWER_SERVICE);
    WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK|PowerManager.ACQUIRE_CAUSES_WAKEUP, "bbbb");
    wl.acquire();
    wl.release();

in the AppWidgetProvider simply the device never wakes up.

Any suggestion more than welcome!

Thanks!!


Solution

  • Well, I used a Handler to call

    wl.release()
    

    after 60 seconds:

    public class AppWidget extends AppWidgetProvider {
    
    @Override
    public void onUpdate(Context ctxt, AppWidgetManager mgr, int[] appWidgetIds) {
        ComponentName thisWidget = new ComponentName(ctxt, AppWidget.class);
        int[] allWidgetIds = mgr.getAppWidgetIds(thisWidget);
        Intent i = new Intent(ctxt, UpdateService.class);
        i.putExtra("widgetsids", allWidgetIds);
        ctxt.startService(i);
    
        PowerManager pm = (PowerManager) ctxt
                .getSystemService(Context.POWER_SERVICE);
        final WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                | PowerManager.ACQUIRE_CAUSES_WAKEUP, "bbbb");
        wl.acquire();
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                wl.release();
            }
        }, 60000);
    
    }