通过硬件按钮启动android应用 [英] Launch an android app by a hardware button

查看:53
本文介绍了通过硬件按钮启动android应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望构建一个可在单击特定硬件按钮时启动的android应用程序.(例如,当我按住调高音量按钮30秒钟时,应用程序必须在不增加音量的情况下启动.)我想知道这可能吗?/p>

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 ?

推荐答案

您可以定义 BroadcastReceiver 来处理 ACTION_MEDIA_BUTTON .接收到的意图包括单个额外的字段 EXTRA_KEY_EVENT ,其中包含导致广播的关键事件.您可以使用此按键事件获取按下的按键并启动您的应用程序.例如,将其添加到您的主要活动中:

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);
}

用主要活动的名称替换 ExampleActivity.class .

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

这篇关于通过硬件按钮启动android应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆