Confused about Android key event handling. Any good explanations? - android

I'm a relative beginner with Android. Does anybody have a sane explanation for how to listen for keys and soft keys in an EditText/TextView?
I'd love to see a comprehensive tutorial or set of examples.
As I understand it, I can add a KeyListener to my Activity, e.g. onKeyDown(), onKeyUp() but when I try this I can't trigger the events for normal keys only HOME and BACK for example.
I have seen mention of using a TextWatcher but that isn't the same as handling raw key events.
There seem to be a number of half-solutions here on SO. Hoping you can help clear the mists of confusion...

You have to assign a key listener not to activity but rather to EditText itself.

This is what I have to listen to BACK or MENU key events. Simply add this method, without implementing any Interface. I do this in my BaseActivity, from which every Activity inherits.
public boolean onKeyDown(int keyCode, KeyEvent event) {
Log.d(NAME, "Key pressed");
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
Log.d(NAME, "Back pressed");
// IGNORE back key!!
return true;
/* Muestra el MenĂº de Opciones */
case KeyEvent.KEYCODE_MENU:
Intent menu = new Intent(this, Menu.class);
// start activity
startActivity(menu);
return true;
}
return super.onKeyDown(keyCode, event);
}
PS: I highly discourage ignoring the back key.

For example:
myEditText.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN)
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER){
//your code here
}
return false;
}
});

I recently found another way that be stuck using Activity onKeyDown, or event setting a key listener on view (which is not really working with key events from ADB in my case) with view.setOnKeyListener.
Since android P method addOnUnhandledKeyEventListener has been introduced. It allows you to do whatever you need to do when your view is able to catch unhandled key events.
Here is an example of how I used it :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) yourView.addOnUnhandledKeyEventListener { v, event ->
when (event.keyCode) {
KeyEvent.KEYCODE_UNKNOWN -> {
TODO("Do whatever you need to do.")
true // Specify you did handle the event
}
KeyEvent.KEYCODE_SOFT_RIGHT -> {
TODO("Do whatever you need to do.")
true // Specify you did handle the event
}
// etc...
else -> false // Specify you didn't handle the event
}
}

Related

Android: Key Event from Android Box remote controller

I was interested to know how can i catch key/button events from Android TV Box remote controller?
For example, i want a popup menu to show when i click the OK button from remote controller. And i want to catch the next/back key events from remote controller.
Should i use the Key Event class from Android, if yes how should i implement it?
I came across this function but i cannot really make sense of it.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_A:
{
//your Action code
return true;
}
}
return super.onKeyDown(keyCode, event);
}
Thanks in advance.
You should catch key event on dispatchKeyEvent
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
Log.e(TAG, "Key down, code " + event.getKeyCode());
} else if (event.getAction() == KeyEvent.ACTION_UP) {
Log.e(TAG, "Key up, code " + event.getKeyCode());
}
return true;
}
Edit:
First, you should know key map of your remote (it is not the same for all kind of Android TV box), the code above will help you know code of key that you press on the remote. For example, i got key code 3 when i press button BACK on remote.
Then, i want when back key pressed, a Toast message will be show:
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
// You should make a constant instead of hard code number 3.
if (event.getAction() == KeyEvent.ACTION_UP && event.getKeyCode == 3) {
Toast.makeText(this, "Hello, you just press BACK", Toast.LENG_LONG).show();
}
return true;
}

Intercept Android system keyboard shortcuts to override functionality

Is it possible for an Android application to intercept external keyboard shortcuts (e.g. Alt+Tab) and action them before the OS performs the default behaviour? Using Alt+Tab as an example, I would like to be able to have my app respond to Alt+Tab within my application and not have Android switch applications to a different app.
I have tried searching, but have not been able to find an answer, I think my Google-Fu is failing me!
It maybe is not as extense or detailed as it would be needed for capturing a shortcut, but you may want to override the onKeyDown event in your activity.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
Log.d(this.getClass().getName(), "Back button pressed");
}
if ((keyCode == KeyEvent.KEYCODE_HOME)) {
Log.d(this.getClass().getName(), "Home button pressed");
}
if ((keyCode == KeyEvent.KEYCODE_MENU)) {
Log.d(this.getClass().getName(), "Menu button pressed");
}
//return true;
return super.onKeyDown(keyCode, event);
}

Can an Android modifier key fallback on an action?

I'm working on an input device that has a button that I'd like to act both as a home button when pressed by itself, but also work as a modifier for the other buttons on the device.
I know you can do this in the kcm file with other buttons, and have something like:
key ESCAPE {
base: fallback BACK
alt, meta: fallback HOME
ctrl: fallback MENU
}
Is it possible to have something like:
key CTRL_LEFT {
base: fallback HOME
{SOMETHING HERE}: CTRL_LEFT
}
so that I can press that button with another button and have it not fallback on HOME?
Thanks in advance! :D
This functionality is not possible on a system level: see
http://source.android.com/tech/input/key-character-map-files.html for a list of all options possible.
However, if you would like to have it on an application level, you could program it in as follows:
import android.view.KeyEvent;
private boolean home = false;
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (event.getScanCode() == 29) //29 == CTRL_LEFT
home = true; //if we release this button, HOME needs to be invoked
else home = false; //so CTRL_LEFT was used as a modifier: no need to invoke HOME
//allow the system to pass key handling to the next listener
return super.onKeyUp(keyCode, event);
}
public boolean onKeyUp(int keyCode, KeyEvent event)
{
if (event.getScanCode() == 29 && home == true)
{
super.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HOME));
return true; //so we absorb the event
}
return super.onKeyUp(keyCode, event);
}
Then, as long as this application is set up to receive the keystrokes (usually a privacy issue unless you're coding it in for yourself), it can process the keystrokes and dispatch the HOME button when need be.
Should you decide to proceed thus, you'd have to remove the
base: fallback HOME
from your code.

onClick HOME key display alert box in android

I am sincerely trying to display alert box onClick of Home key, but I am not succeeded. So please help me to write the code otherwise, show me the code.
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK )
{
finish();
return false;
}
else if (keyCode == KeyEvent.KEYCODE_HOME)
{
finish();
return false;
}
return super.onKeyDown(keyCode, event);
}
it is not possible to intercept KEYCODE_HOME by external applications:
http://code.google.com/p/android/issues/detail?id=1979
I don't think you can intercept HOME key presses. It is reserved to ensure that you don't get locked within any application.
KEYCODE_HOME : This key is handled by the frame work and is never delivered to applications.
So you can't use it

Bringing up SoftKeyboard on android

I want to pop up the software keyboard when the user presses the search hardware search key.
At the moment I use the following function with doesn't seem to work for the search key but which does work for the back key:
The logging doesn't get even tiggered through the search key.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK){
Log.v(TAG, "On back key press");
renderPrevious();
return false;
}
if(keyCode == KeyEvent.KEYCODE_SEARCH){
Log.v(TAG, "On search key press");
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
return false;
}
return true;
}
I have no text field but want to handle the input directly myself if that matters.
this method setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE) doesnt wakeup the keyboard. Check this link. More to know about it check this example. hope it helps
Edit:
try this showSoftInput method
Maybe this would be helpful:
InputMethodManager inputMgr = (InputMethodManager)getSystemService Context.INPUT_METHOD_SERVICE);
inputMgr.toggleSoftInput(0, 0);
http://plainoldstan.blogspot.com/2010/09/android-set-focus-and-show-soft.html
"When experimenting I was not actually getting what I wanted until I realized I should have an emulator device with no hardware keyboard:"

Categories

Resources