如何显示屏幕已锁定?

发布于 2024-11-10 15:13:56 字数 81 浏览 2 评论 0原文

在我的应用程序中,我需要知道设备何时被锁定(在 HTC 上,它看起来像是短按“电源”按钮)。那么问题是:设备锁定时会触发哪个事件?或者设备将要休眠?

In my application I need to know when device is locked (on HTC's it looks like short press on "power" button). So the question is: which event is triggered when device is locked? Or device is going to sleep?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

预谋 2024-11-17 15:13:56

您应该扩展 BroadcastReceiver 并实现 onReceive,如下所示:

public class YourBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_SCREEN_OFF.equalsIgnoreCase(intent.getAction())) {
            //screen has been switched off!
        }
    }
}

然后您只需注册它,当屏幕关闭时您将开始接收事件:

IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
appBroadcastReceiver = new AppBroadcastReceiver(yourActivity);
registerReceiver(appBroadcastReceiver, filter);

You should extend BroadcastReceiver and implement onReceive, like this:

public class YourBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_SCREEN_OFF.equalsIgnoreCase(intent.getAction())) {
            //screen has been switched off!
        }
    }
}

Then you just have to register it and you'll start receiving events when the screen is switched off:

IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
appBroadcastReceiver = new AppBroadcastReceiver(yourActivity);
registerReceiver(appBroadcastReceiver, filter);
不奢求什么 2024-11-17 15:13:56

有一个更好的方法:

KeyguardManager myKM = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if( myKM.inKeyguardRestrictedInputMode()) {
 //it is locked
} else {
 //it is not locked
}

There is a better way:

KeyguardManager myKM = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if( myKM.inKeyguardRestrictedInputMode()) {
 //it is locked
} else {
 //it is not locked
}
灯角 2024-11-17 15:13:56

除了上述答案之外,如果您想在应用程序位于前台时触发某些操作:

您可以使用名为onResume()的事件来触发您的应用程序当您的应用程序从之前的静止状态中获得关注时,即,如果您的应用程序位于后台(暂停/最小化...)

protected void onResume()
{
    super.onResume();

    //call user-defined function here
}

In addition to the above answer, in-case you want to trigger some action when your app is at the foreground:

You could use the event called onResume() to trigger your own function when your app takes the spotlight from a previously resting state, i.e, if your app was at the background(paused/minimized...)

protected void onResume()
{
    super.onResume();

    //call user-defined function here
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文