如何“屏幕开启”,来自服务?

时间:2013-12-26 15:27:22

标签: android service screen

我需要从service打开屏幕,我试过这个:

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
wl.acquire();

我看过几篇帖子并没有为我工作过,你推荐什么?

1 个答案:

答案 0 :(得分:0)

尝试这样做:

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
        PowerManager.ACQUIRE_CAUSES_WAKEUP |
        PowerManager.ON_AFTER_RELEASE,
        "My Tag");
wl.acquire();

由于唤醒锁太危险,您必须在完成工作后将其释放。在您的情况下,注册一个接收器来监听Intent.ACTION_SCREEN_ON。要意识到这个意图必须动态注册,即你不能在AndroidManifest.xml中的intent-filter中使用它。

在您的服务类中:

private WakeLock mWakeLock; // Remember to use this field instead of wl in above code

private BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent != null) {
            if (Intent.ACTION_SCREEN_ON.equals(intent.getAction())) {
                if (mWakeLock != null && mWakeLock.isHeld()) {
                    mWakeLock.release();
                    mWakeLock = null;
                }
            }
        }
    }
};

@Override
public void onCreate() {
    super.onCreate();

    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_SCREEN_ON);
    registerReceiver(mReceiver, filter);
}

并且不要忘记添加AndroidManifest.xml

<uses-permission android:name="android.permission.WAKE_LOCK" />
祝你好运!