Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Launch an android app by a hardware button

Tags:

android

I hope to build an android application which launches when specific hardware button clicks.(As an example when I press the volume up button for 30 seconds app must launch without increasing the volume. ) I want to know is this possible ?

like image 398
Hasitha Thamaranga Avatar asked Jun 12 '26 16:06

Hasitha Thamaranga


1 Answers

You could define a BroadcastReceiver to handle ACTION_MEDIA_BUTTON. The received intent includes a single extra field EXTRA_KEY_EVENT which contains the key event that caused the broadcast. You can use this key event to get which key was pressed and to launch your app. For example, add this to your main activity:

public void onCreate(Bundle savedInstanceState) {

    HardwareButtonReceiver receiver = new HardwareButtonReceiver();

    registerMediaButtonEventReceiver(receiver);

}

private class HardwareButtonReceiver implements BroadcastReceiver {
     void onReceive(Intent intent) {
          KeyEvent e = (KeyEvent) intent.getExtra(Intent.EXTRA_KEY_EVENT); 
          if(e.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) {
              launchApp();
          }
     } 
}

private void launchApp() {
    Intent intent = new Intent(getApplicationContext(), ExampleActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    startActivity(intent);
}

Replace ExampleActivity.class with the name of your main activity.

like image 190
tpbapp Avatar answered Jun 15 '26 07:06

tpbapp