Search code examples
javaandroidwidgetwakelockandroid-wake-lock

How to use getSystemService in widget on android?


I want to use wake lock to keep screen on by clicking widget on desktop

code here:

final PowerManager pm = (PowerManager)getSystemService(context.POWER_SERVICE);
PowerManager.WakeLock mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "");
mWakeLock.acquire();

but it says getSystemService can not be used if it is not "extends activity".

please help


Solution

  • When you extend AppWidgetProvider all methods have a Context object passed in.

    The getSystemService method is part of the Context class in Android, so you will be able to get it using the passed in context.

    See: Context and getSystemService on Android Developers

    Example code:

    public class TestWidget extends AppWidgetProvider {
    
        @Override
        public void onEnabled(Context context) {
            super.onEnabled(context);
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        }
    }
    

    The example code uses the onEnabled method as an example, but this also works in the other methods like onDisabled, onUpdate, onAppWidgetOptionsChanged etc.