Android Device Bottom Key Panel Management Programatically

There are various Android Application where we need to control the android bottom key panel. This bottom key panel is organised by five keys

1. Back
2. Menu
3. Home
4. Search
5. Settings

If we take any example like online payment Application then we can’t allow a user to press the back button in the middle of payment. So we have to override the back press event and managed the click event.

There are many cases where we provide certain action of the application like action bar menu will be appeared when menu button user will pressed.

This key panel button events are identified by android in following ways

1. Back – KEYCODE_BACK
2. Menu -KEYCODE_MENU
3. Home – KEYCODE_HOME
4. Search – KEYCODE_SEARCH
5. Settings – KEYCODE_SETTINGS

For handling this keys we need to override this method of the Activity

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

if (keyCode == KeyEvent.KEYCODE_BACK) {
//Do Code Here
// If want to block just return false
return false;
}
if (keyCode == KeyEvent.KEYCODE_MENU) {
//Do Code Here
// If want to block just return false
return false;
}
if (keyCode == KeyEvent.KEYCODE_HOME) {
//Do Code Here
// If want to block just return false
return false;
}
if (keyCode == KeyEvent.KEYCODE_SEARCH) {
//Do Code Here
// If want to block just return false
return false;
}
if (keyCode == KeyEvent.KEYCODE_SETTINGS) {
//Do Code Here
// If want to block just return false
return false;
}

return super.onKeyDown(keyCode, event);
}

From Android 4.0 (ICS) onward KEYCODE_HOME has been deprecated. As Android believed that it is wrong to give all the option blocked for user. User can pressed the Home button to navigate to other application. But android keep the current application as it is state in the background. So that user can back to the previous application.

There are another instance user can accidentally press back button and exit the application. In that case we have to give alert to the user before quit the application. For that we need to identify for the last activity in the stack. For that we need to identify and checked for the last activity form the stack.

private boolean isLastActivity() {
final ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
final List tasksInfo = am.getRunningTasks(1024);

final String ourAppPackageName = getPackageName();
RunningTaskInfo taskInfo;
final int size = tasksInfo.size();
for (int i = 0; i < size; i++) {
taskInfo = tasksInfo.get(i);
if (ourAppPackageName
.equals(taskInfo.baseActivity.getPackageName())) {
return taskInfo.numActivities == 1;
}
}
return false;
}

So we can use this android device bottom key panel to Application short key.