Can we update UI by overriding hardware buttons in Android

98 views Asked by At

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.

3

There are 3 answers

0
Shailendra Madda On

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);
            }
        }
0
markt On
public boolean onKey(View v, int keyCode, KeyEvent event) {
    switch (keyCode) {
        case KeyEvent.KEYCODE_VOLUME_DOWN:


        break;
    }
    return false;
}
  • should do it.
0
Adeel Ahmad On

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.