我希望构建一个在特定硬件按钮点击时启动的Android应用程序。(例如,当我按下音量增大按钮30秒时,app必须在不增加音量的情况下启动。)我想知道这可能吗?< / p>
答案 0 :(得分:1)
您可以定义BroadcastReceiver
来处理ACTION_MEDIA_BUTTON
。所接收的意图包括单个额外字段EXTRA_KEY_EVENT
,其包含导致广播的关键事件。您可以使用此键事件来获取按下的键并启动您的应用。例如,将其添加到您的主要活动:
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);
}
将ExampleActivity.class
替换为您的主要活动名称。