I want to listen for an Android key press. For example when I press the Menu key on the phone, I will get this key press and start an application.
And I don't know in Phonewindowmanager.java
when I pressed a key, t开发者_Python百科he interceptKeyTq()
come to twice.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
//do something
}
return true;
}
Hope this helps.
Here is a simple test program. don't forget setFocusable(true) and invalidate().
Insted of using System.out, you can use Log - http://code.google.com/android/reference/android/util/Log.html
public class HelloAndroid extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(new MyView(this));
}
class MyView extends View {
private static final String LOGID = "MxView";
String message = "No key pressed yet.";
MyView(Context context) {
super(context);
setFocusable(true);
}
@Override
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
canvas.drawText(message, 5, 20, paint);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent ev) {
switch(keyCode) {
case KeyEvent.KEYCODE_DPAD_UP:
message = "Key Up!";
Log.i(LOGID, message);
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
message = "Key Down!";
Log.i(LOGID, message);
break;
default:
return false;
}
invalidate();
return true;
}
}
}
精彩评论