juliet
juliet

Reputation: 897

Global method in Android App?

I am very new to Android and I need my app to listen out for a specific key being pressed at all times. I have managed to get this working in each activity with the following code:

@Override
public boolean dispatchKeyEvent(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.KEYCODE_F) {
        Log.d("Test","YOU PRESSED THE F KEY");
        startActivity(new Intent(getApplicationContext(), Activity2.class));
        return true;
    }
    return super.dispatchKeyEvent(e);
};

However, I am trying to figure out if I could just have this method once somewhere in the code? (Rather than have this piece of code in each individual activity)

Upvotes: 2

Views: 570

Answers (3)

Dan Harms
Dan Harms

Reputation: 4840

Create a new abstract activity which all of your activities can extend.

public abstract class BaseActivity extends Activity {
    @Override
    public boolean dispatchKeyEvent(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.KEYCODE_F) {
            Log.d("Test","YOU PRESSED THE F KEY");
            startActivity(new Intent(getApplicationContext(), Activity2.class));
            return true;
        }
        return super.dispatchKeyEvent(e);
    }

}

Upvotes: 2

ucsunil
ucsunil

Reputation: 7494

Yes, you can do it by first defining an abstract parent activity that holds this method and then inherit from this activity

Upvotes: 1

Display Name
Display Name

Reputation: 8128

You can define an abstract base class that extends Activity and overrides dispatchKeyEvent like you did, and then make all activities subclasses of this class.
Maybe you want to read this tutorial.

Upvotes: 1

Related Questions