2017-05-11 82 views
-2

如何在同時按下多個按鍵(如使用電源和音量鍵啓動恢復和下載模式時)在Android應用程序中啓動新的活動?Android多按鈕按

@Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) 
    { 
     if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) 
     { 
      Intent intent = new Intent(this, SettingsActivity.class); 
      startActivity(intent); 
     } 
     return true; 
    } 

回答

1

請嘗試以下解決方案,測試和它的作品!

public class MainActivity extends AppCompatActivity { 
    private boolean isVolumeUpPressed = false; 
    private boolean isVolumeDownPressed = false; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
    } 

    @Override 
    public boolean onKeyDown(final int keyCode, final KeyEvent event) { 
     if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { 
      this.isVolumeDownPressed = true; 
     } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) { 
      this.isVolumeUpPressed = true; 
     } 
     if (this.isVolumeUpPressed && this.isVolumeDownPressed) { 
      final Intent intent = new Intent(this, SettingsActivity.class); 
      startActivity(intent); 
     } 
     return super.onKeyUp(keyCode, event); 
    } 

    @Override 
    public boolean onKeyUp(final int keyCode, final KeyEvent event) { 
     if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { 
      this.isVolumeDownPressed = false; 
     } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) { 
      this.isVolumeUpPressed = false; 
     } 
     return super.onKeyUp(keyCode, event); 
    } 
} 
+0

非常感謝你的工作。你可以告訴我如何使音量提高+音量提高+音量降低+家庭+電力+家庭嗎? –

+0

@Pavle_nis不客氣。你有多少個音量調節鈕和按鈕? XD – AlexTa

+0

兩倍音量調高+音量降+家+電+家! –

0
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) && (keyCode == KeyEvent.KEYCODE_VOLUME_UP)) { 
+0

它不起作用! –

+0

在這個例子中,向上和向下鍵被處理。 KeyEvent.KEYCODE_POWER嘗試它。 –

+0

我在同一時間按下了音量調高鍵和音量調低鍵,沒有任何反應! –