有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在安卓上的widget中使用getSystemService?

我想通过点击桌面上的小部件来使用唤醒锁来保持屏幕打开

代码如下:

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

但是它说getSystemService不能被使用 如果不是“扩展活动”

请帮忙


共 (2) 个答案

  1. # 1 楼答案

    扩展AppWidgetProvider时,所有方法都会传入一个Context对象

    getSystemService方法是Android中Context类的一部分,因此您可以使用传入的上下文获取它

    见:Context and getSystemService on Android Developers

    示例代码:

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

    示例代码使用onEnabled方法作为示例,但这也适用于其他方法,如onDisabledonUpdateonAppWidgetOptionsChanged

  2. # 2 楼答案

    在非活动类或小部件中使用getSystemService时,需要使用适当的context

    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();
    

    并将camel caseContext用于Context.POWER_SERVICE

    希望这有帮助