2011-05-31 105 views
9

在我的应用程序中,我需要知道设备何时被锁定(在HTC上它看起来像短按“电源”按钮)。所以问题是:设备被锁定时触发哪个事件?或设备将要睡觉?如何揭示该屏幕被锁定?

回答

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); 
+0

看起来太棒了!我会马上查看! – barmaley 2011-05-31 11:25:44

+0

是的,它的工作原理!非常感谢! – barmaley 2011-05-31 15:42:53

+0

@barmaley乐于帮助! – pandre 2011-05-31 17:37:50

0

除了上述答案之外,如果您希望在应用处于前景时触发某些操作

您可以使用事件称为的onResume()触发自己的功能,当你的应用程序需要的焦点从之前休息状态,也就是说,如果您的应用程序在后台(暂停/最小化......)

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

    //call user-defined function here 
} 
+0

不,这不适合,因为onResume()每次在活动开始时都会调用,因此不会在睡眠后创建线索,或者仅创建 – barmaley 2011-05-31 11:24:27

+0

yup。肯定。只是一个建议:) – Augiwan 2011-05-31 13:38:31

3

有一个更好的办法:

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

你尝试过isDeviceLocked为Android 5.1 http://developer.android.com/reference/android/app/KeyguardManager.html#isDeviceLocked()? – 2015-04-03 10:05:21