我正在制作一个锁屏应用程序,它使用前台服务,启动时禁用键盘保护,销毁时重新启用。我可以很好地禁用它,但当服务停止时它将无法重新启用。我在一个活动中停止服务,我知道调用ondestroy()是因为通知消失了。我的服务代码:

@Override
public void onDestroy() {
    isRunning = false;
    KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Service.KEYGUARD_SERVICE);
    KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
    lock.reenableKeyguard();
    stopForeground(true);
    super.onDestroy();
}



@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Service.KEYGUARD_SERVICE);
    KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
    lock.disableKeyguard();

    Notification notification = new Notification(R.drawable.ic_launcher, getText(R.string.ticker_text),
            System.currentTimeMillis());
    Intent notificationIntent = new Intent(this, LockService.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    notification.setLatestEventInfo(this, getText(R.string.notification_title),
            getText(R.string.notification_message), pendingIntent);
    startForeground(1, notification);

    return Service.START_STICKY;
}

}

最佳答案

要禁用(解锁)钥匙锁,请使用以下代码。这将创建一个新的keyguardlock并使用它来禁用keyguard

KeyguardLock keyguardLock = keyguardManager.newKeyguardLock(“Keyguard_Lock_Test”);
keyguardLock.disableKeyguard();

要重新启动键盘护面,请使用以下线路释放锁。如果首先锁定了keyguard,并且当前没有应用程序持有keyguard锁,则此操作将锁定keyguard
keyguardLock.reenableKeyguard();
keyguardLock = null;

07-24 09:48
查看更多