如何从Application类隐藏键盘?

时间:2016-04-09 20:56:06

标签: android android-activity android-softkeyboard

我正在使用此代码隐藏我从这里获得的软键盘:Close/hide the Android Soft Keyboard

public class HideKeyboardUtils {

    public static void hideKeyboard(Activity activity) {
        InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        //Find the currently focused view, so we can grab the correct window token from it.
        View view = activity.getCurrentFocus();
        //If no view currently has focus, create a new one, just so we can grab a window token from it
        if(view == null) {
            view = new View(activity);
        }
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
}

在我的Application类中,每次我的应用程序崩溃时,此函数都会运行,以便在应用程序崩溃时隐藏键盘:

    final Thread.UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread thread, Throwable throwable) {
            HideKeyboardUtils.hideKeyboard( // how do I get an instance of an activity here?);
        }
    });

我不知道如何在我的Application类中获取活动的实例,并且从阅读此线程看起来似乎不可能 - Getting Main Activity from Main Application

我看到我需要活动,以便我可以从活动中获取视图以获取WindowToken。有没有办法在应用程序类中获取视图,以便键盘隐藏在应用程序崩溃?

请参阅下面的崩溃示例:

enter image description here

0 个答案:

没有答案