2011-05-31 88 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