How to use getSystemService in widget on android?

2.7k views Asked by At

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

2

There are 2 answers

0
Rolf ツ On BEST ANSWER

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.

0
MysticMagicϡ On

You will need to use proper context for using getSystemService in a non-activity class or Widget.

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

And use camel case Context for Context.POWER_SERVICE

Hope this helps.