我目前正試圖聽電源按鈕何時按下。最終我想在按兩次電源按鈕時運行一些代碼,以檢查屏幕是否鎖定或解鎖。我目前有這樣的:Android:聽電源鍵按
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);//prevent phone from being locked
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_POWER:
{
Toast.makeText(getBaseContext(), "Power button pressed", Toast.LENGTH_LONG).show();
return true;
}
case KeyEvent.KEYCODE_MENU:
Toast.makeText(getBaseContext(), "Menu Button Pressed", Toast.LENGTH_LONG).show();
return true;
}
return super.onKeyDown(keyCode, event);
}
該代碼工作正常,爲菜單鍵事件烤麪包,但不爲電源鍵事件做任何事情。有任何想法嗎?
有這個沒有API,但你可以使用反射實現它。 http://stackoverflow.com/a/31872330/3496570 – Nepster