Is it possible to write an Android broadcast receiver that detects when the phone wakes up?

笑着哭i 提交于 2019-11-27 18:21:22

问题


I want to figure out how to detect when the phone wakes up from being in the black screen mode and write a handler for that event. Is that possible? It seems like this would be something a Broadcast Receiver should handle? Or is there a better or more proper way?


回答1:


If you have a Service that it active you can catch these events with

registerReceiver(new BroadcastReceiver() {

  @Override
  public void onReceive(Context context, Intent intent) {
    // do something
  }
}, new IntentFilter(Intent.ACTION_SCREEN_ON));

However this relies on having a perpetually running service which I have recently learned is discouraged because it is brittle (the OS likes to close them) and uses resources permanently.

Disappointingly, it seems it is not possible to have a receiver in your manifest that intercepts SCREEN_ON events.

This has come up very recently:

android.intent.action.SCREEN_ON doesn't work as a receiver intent filter

also

Android - how to receive broadcast intents ACTION_SCREEN_ON/OFF?




回答2:


You could also have a broadcast receiver that catches the USER_PRESENT broadcast intent for when the user has unlocked the device. Naturally some versions of Honeycomb don't honor this but for all non brain-dead versions of Android (2.x and 4.x), it works nicely.




回答3:


You are right on the broadcast receiver. You could listen to the SCREEN_ON and SCREEN_OFF broadcast events.



来源:https://stackoverflow.com/questions/2577318/is-it-possible-to-write-an-android-broadcast-receiver-that-detects-when-the-phon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!