I want to open a alertbox by pressing volume down button even if my app is closed. Please help me and do tell if it is possible or not.
Asked
Active
Viewed 97 times
0
-
`even if my app is closed` then you need to use background Service – SweetWisher ツ Nov 14 '14 at 12:22
-
[have a look here](http://stackoverflow.com/a/12793599/2591002) and [Services simply do not receive KeyEvent callbacks](http://stackoverflow.com/a/11397294/2591002) – SweetWisher ツ Nov 14 '14 at 12:26
3 Answers
1
The other answers will only work if app is not closed. OP asked if he can do that even if the app is closed. In simple words, that is not possible because even by creating a service in background, it wont work as services don't receive key callback events. This post shows a workaround, you can go ahead and try that however chances of it working in every ROM are low.

Community
- 1
- 1

Adeel Ahmad
- 939
- 1
- 10
- 20
0
Try this:
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
int action = event.getAction();
int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
if (action == KeyEvent.ACTION_DOWN) {
//Alert dialog code here
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle("Your Title");
// set dialog message
alertDialogBuilder
.setMessage("Click yes to exit!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
MainActivity.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (action == KeyEvent.ACTION_DOWN) {
//TODO
}
return true;
default:
return super.dispatchKeyEvent(event);
}
}

Shailendra Madda
- 20,649
- 15
- 100
- 138
0
public boolean onKey(View v, int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_DOWN:
break;
}
return false;
}
- should do it.

markt
- 903
- 7
- 21