简体   繁体   中英

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)

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);
    }

}

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 .

是的,您可以先定义一个抽象父活动来保存此方法,然后再从该活动继承,以实现此目的

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM