Today I amazed that why my menu doesn’t show when i put onKeyDown() in my code!!!
in my project i have menu and i designed it with onCreateOptionsMenu() and onOptionsItemSelected() in regular way. The project doesn’t have problem and works fine.
The problem is using onKeyDown(). when i put it into my activity and run the project, when i click on menu button, it doesn’t show anything. while when i comment out onKeyDown() the app works fine.
What is the reason? Thank you
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return (super.onCreateOptionsMenu(menu));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.home:
Log.i("Menu", "Home clicked.");
return true;
case R.id.social:
Log.i("Menu", "Social Networks clicked.");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
if(keyCode == KeyEvent.KEYCODE_HOME){
Log.i("onKeyDown", "Home presed");
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
}
if(keyCode == KeyEvent.KEYCODE_BACK){
Log.i("onKeyDown", "back presed");
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
}
return true;
}
When you return a value from the
onKeyDown()method, it indicates whether the event has been handled or not. In your casetrueis always returned regardless of whether you have really responded to the event or not. The correct version of the method should be:Also, I should say that killing the process on the button clicks is not how such things are handled in Android, you should manage your activity instead. Back button finishes activity by default, and you should leave this as that, restarting activity on launch is specified in AndroidManifest.xml.