2

I am creating an application and want to do some action when volume button is pressed four times. I am doing like this and its working fine.

public boolean onKeyDown(int keyCode, KeyEvent event) 
{ 
   if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP) { 
       count++;
       if(count==4){
          dosomething();
          return true;
       }
       else
          return false;
   } 
}

The problem is that my app is running in the background and as Services are not intended to react on user input so what can be a work around here how can I call my function let say dosomething() on user input when app is in background. It is the most important part of the application because otherwise purpose of application is destroyed. It cant not necessarily be a volume button, if home or any other works then its fine too. Will really appreciate if anyone can help me.

Hamza
  • 1,593
  • 2
  • 19
  • 31
  • @JesusS See this http://stackoverflow.com/questions/6712601/android-capturing-volume-up-down-key-presses-in-broadcast-receiver This says that broadcast receiver doesnot work in background services. – Hamza Feb 20 '14 at 12:25
  • 1
    Sure they do ;) : http://stackoverflow.com/questions/9092134/broadcast-receiver-within-a-service . Regards – JesusS Feb 20 '14 at 12:26

2 Answers2

1

Here's what you can do:

  • It is correct that you cant get KeyEvents from a Service.

  • but you can use BroadcastReceivers to listen for a specific user inputs and use them in your Service.

Have a look at the following:

Android BroadCastReceiver for volume key up and down

BroadcastReceivers

Android BroadcastReceiver Tutorial

Broadcast Receiver within a Service

Community
  • 1
  • 1
SMR
  • 6,628
  • 2
  • 35
  • 56
0

Afaik, there is no way using the Service to intercept the volume button, home, back, power button keys.

As @SMR suggested you can use the BroadcastReceiver only for volume and power buttons.

BroadcastReceiver - android.media.VOLUME_CHANGED_ACTION execute when media volume change.

but this receiver wont call when your device is locked. If you want to make your volume button active then you have to run a media file in the background that is not good solution. I am recommending you for not to use this for making volume button active because it will drain the battery of the device and will change the stream behavior of the device.

You can register the Screen_ON and Screen_OFF BroadcastReceiver which execute when your device screen ON/OFF

Link : http://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/

Ajay S
  • 48,003
  • 27
  • 91
  • 111