Viktor Apoyan
Viktor Apoyan

Reputation: 10755

Receive volume key press events when phone is in deep sleep

I'm trying to catch Volume Up/Down pressing events when phone is in deep sleep mode. I have read several articles and here what I have done.

In Activities onCreate method I set a WakeLock

PowerManager mgr = (PowerManager)this.getSystemService(Context.POWER_SERVICE);
WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
wakeLock.acquire();

I have read that even if my screen is locked if I set this my application will respond to events. Also I have added permission in to Android Manifest.

<uses-permission android:name="android.permission.WAKE_LOCK" />

Then in the onCreate method I declare my Broadcast Receiver

VolReceiver volumeBroadcastReceiver = new VolReceiver();

IntentFilter filter = new IntentFilter();
filter.addAction("android.media.VOLUME_CHANGED_ACTION");
registerReceiver(volumeBroadcastReceiver, filter);

This all works pretty good then application is in foreground or background, but then I lock my phones screen by pressing on a power button application stop receiving broadcast events, I think that PowerManager must solve this issue but it doesn't. So please help me, provide some information.

Upvotes: 1

Views: 4047

Answers (2)

CommonsWare
CommonsWare

Reputation: 1006539

I'm trying to catch Volume Up/Down pressing events when phone is in deep sleep mode.

By definition, that is impossible.

In Activities onCreate method I set a WakeLock

Then you are not in sleep mode.

then I lock my phones screen by pressing on a power button application stop receiving broadcast events

There are a few possibilities here. One is that your process was terminated, as it is no longer needed. Once you no longer have any foreground activities, your process is eligible to be terminated to free up memory for other apps, and that can happen at any point. Another possibility is that Android simply does not send that broadcast when the screen is off.

Upvotes: 2

nam_ph
nam_ph

Reputation: 233

I did pretty much the same thing, but i achieved it by changing the source codes. i have explained that below.

whenever your phone goes to sleep , your MediaPlaybackService.java will not listen to keyEvents, but MediaButtonIntentReceiver.java will, so receive the intent here of volume up and down, and broadcast an intent and receive it in MediaPlaybackService.java, but keep one thing in mind you can't change the UI from here , so you can broadcast another intent from the service and make your MediaPlaybackActivity.java receive it , this will change the UI as soon as your screen wakes up.

FYI: when the screen is off, the PhoneWindowManager.java queues all the continuous intents and as soon as you release the button it will apply all the intents at once.

Upvotes: 2

Related Questions