在我的应用程序中,我需要知道设备何时被锁定(在HTC上它看起来像是短按“电源”按钮)。所以问题是:当设备被锁定时会触发哪个事件?或设备要睡觉了吗?
答案 0 :(得分:5)
您应该扩展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);
答案 1 :(得分:3)
有一种更好的方法:
KeyguardManager myKM = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if( myKM.inKeyguardRestrictedInputMode()) {
//it is locked
} else {
//it is not locked
}
答案 2 :(得分:0)
除上述答案外,如果您的应用位于前景,您希望触发某些操作:
您可以使用名为 onResume()的事件触发您自己的功能,当您的应用从之前的静止状态获得聚光灯时,即,如果您的应用处于后台(暂停/最小化)。 ..)
protected void onResume()
{
super.onResume();
//call user-defined function here
}