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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With