2

Alright, so i am having some problems trying to get a broadcast receiver and service to work properly with screen off and screen on.

What i am trying to do is start something when the screen goes off or when the screen goes on. I got it to work from an activity for testing, but the activity must be currently running. I need it to start from the background pretty much.

Now, i know that using the intent filters in the manifest does not work for screen_off and on. How would i be able to do this? I guess this would work sort of like a lockscreen...

Screen off --> starts something (example activity or create a log message as a toast wouldn't work)

user1190019
  • 565
  • 1
  • 5
  • 17
  • "Now, i know that using the intent filters in the manifest does not work for screen_off and on." - How do you 'know' this? Why wouldn't it work? – Squonk Mar 11 '12 at 03:59
  • Research and reading. Also tried it out... http://stackoverflow.com/questions/2575242/android-intent-action-screen-on-doesnt-work-as-a-receiver-intent-filter is another example – user1190019 Mar 11 '12 at 05:12
  • So why didn't you put that link in your own question in order to qualify how you know this? More importantly, however, why don't you take the advice of the answer to that question? The long and short of it is...if you have a running `Activity` or `Service` then you can register a `BroadcastReceiver` to listen for those events and it will exist for the lifetime of those objects. You shouldn't, however, expect to be able to 'globally' monitor them. After all, if I press the 'On' button on my phone just to check the time on the lock screen, why would I want YOUR app to do anything? – Squonk Mar 11 '12 at 07:18
  • Well, an example of why you would want MY app to do something is if it was a lock screen or something that overlays part of the lock screen, sort of like a widget... – user1190019 Mar 13 '12 at 04:56

1 Answers1

0

Add a receiver:

public class BroadcastReceiverScreenListener extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    if (Objects.equals(intent.getAction(), Intent.ACTION_SCREEN_OFF)) {

        ** Do your stuff**

    }
}

From the docs: You cannot receive this through components declared in manifests, only by explicitly registering for it with registerReceiver(BroadcastReceiver, IntentFilter) This is a protected intent that can only be sent by the system.

Ziv Kesten
  • 1,206
  • 25
  • 41