2010-11-17 163 views

回答

11

系统将广播 -

为了听这些,你可以创建一个侦听事件一个BroadcastReceiver:

Intent.ACTION_SCREEN_OFF Intent.ACTION_SCREEN_ON

他们的文档here中列出:

此外,还有一个tutorial关于应对这些事件,你可能会发现使用FUL。

+5

有具有相同的答案,一个拷贝之间的差异。我们做了相同的谷歌搜索是:P – 2010-11-22 20:32:23

+0

仔细阅读文档!这个答案实际上告诉你,如果设备是“互动”。如果屏幕被锁定,则设备不是交互式的。如果显示硬件当前处于打开状态,则只有'android.hardware.display.DisplayManager'可以告诉你。但是,这可能需要Android 5. – OneWorld 2016-09-29 11:02:40

19

最简单的方法就是把这个在您的MyApplication.onCreate()方法:

IntentFilter intentFilter = new IntentFilter(Intent.ACTION_SCREEN_ON); 
intentFilter.addAction(Intent.ACTION_SCREEN_OFF); 
registerReceiver(new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { 
      Log.d(TAG, Intent.ACTION_SCREEN_OFF); 
     } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { 
      Log.d(TAG, Intent.ACTION_SCREEN_ON); 
     } 
    } 
}, intentFilter); 
+0

感谢这很好,应该标记为答案。 – pmont 2014-04-22 22:10:13

+0

在这种情况下如何以及何时注销Receiver? – 2015-03-17 09:16:04

+1

你可以在任何你喜欢的地方调用[unregisterReceiver()](http://developer.android.com/reference/android/content/Context.html#unregisterReceiver(android.content.BroadcastReceiver))。但是假设你将上面的代码放在'MyApplication.onCreate()'中,你不会这么做,因为没有Application.onDestroy()函数(Application类是唯一的 - 请参阅官方文档或[这里](http://stackoverflow.com/questions/17278201/android-ondestroy-or-similar-method-in-application-class)获取更多信息)。 – 2015-03-17 20:34:37