1 /* 2 * Copyright (C) 2017 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.android.launcher3.util; 17 18 import android.content.Context; 19 import android.os.Handler; 20 import android.os.HandlerThread; 21 import android.os.IBinder; 22 import android.os.Looper; 23 import android.os.Message; 24 import android.os.Process; 25 import android.view.inputmethod.InputMethodManager; 26 27 /** 28 * Utility class for offloading some class from UI thread 29 */ 30 public class UiThreadHelper { 31 32 private static HandlerThread sHandlerThread; 33 private static Handler sHandler; 34 35 private static final int MSG_HIDE_KEYBOARD = 1; 36 getBackgroundLooper()37 public static Looper getBackgroundLooper() { 38 if (sHandlerThread == null) { 39 sHandlerThread = 40 new HandlerThread("UiThreadHelper", Process.THREAD_PRIORITY_FOREGROUND); 41 sHandlerThread.start(); 42 } 43 return sHandlerThread.getLooper(); 44 } 45 getHandler(Context context)46 private static Handler getHandler(Context context) { 47 if (sHandler == null) { 48 sHandler = new Handler(getBackgroundLooper(), 49 new UiCallbacks(context.getApplicationContext())); 50 } 51 return sHandler; 52 } 53 hideKeyboardAsync(Context context, IBinder token)54 public static void hideKeyboardAsync(Context context, IBinder token) { 55 Message.obtain(getHandler(context), MSG_HIDE_KEYBOARD, token).sendToTarget(); 56 } 57 58 private static class UiCallbacks implements Handler.Callback { 59 60 private final InputMethodManager mIMM; 61 UiCallbacks(Context context)62 UiCallbacks(Context context) { 63 mIMM = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); 64 } 65 66 @Override handleMessage(Message message)67 public boolean handleMessage(Message message) { 68 switch (message.what) { 69 case MSG_HIDE_KEYBOARD: 70 mIMM.hideSoftInputFromWindow((IBinder) message.obj, 0); 71 return true; 72 } 73 return false; 74 } 75 } 76 } 77