先安装想要设置默认的输入法
获取系统已安装的输入法ID
/**
* 获取系统已安装的输入法ID
*
* @param context
* @return
*/
public static String[] getInputMethodIdList(Context context) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null && imm.getInputMethodList() != null) {
String[] methodIds = new String[imm.getInputMethodList().size()];
for (int i = 0; i < imm.getInputMethodList().size(); i++) {
methodIds[i] = imm.getInputMethodList().get(i).getId();
}
return methodIds;
}
return new String[]{};
}
写入系统数据库
/**
* 设为系统默认输入法
* (写入Android系统数据库)
*/
public static void setDefaultInputMethod(Context context) {
String key = Settings.Secure.DEFAULT_INPUT_METHOD;
//读取默认输入法
String current = Settings.Secure.getString(context.getContentResolver(), key);
Log.d("TAG", "current default: " + current);
if (current.contains("com.cootek.smartinputv5")) {
return;
}
//获取系统已安装的输入法ID
String[] methods = getInputMethodIdList(context);
if (methods.length == 0) {
Log.w("TAG", "found no input method.");
return;
}
//检查是否是你要设置的输入法
//触宝输入法ID "com.cootek.smartinputv5/com.cootek.smartinput5.TouchPalIME";
String targetKeyword = "com.cootek.smartinputv5";
String value = "";
for (String m : methods) {
Log.d("TAG", String.format("find : %s", m));
if (m.toLowerCase().contains(targetKeyword.toLowerCase())) {
value = m;//找到触宝输入法
}
}
if (value.equals("")) {
Log.w("TAG", "didn't find " + targetKeyword);
return;
}
//将该输入法打开,不打开设置默认输入法会无效
Settings.Secure.putString(context.getContentResolver(), Settings.Secure.ENABLED_INPUT_METHODS,value);
//设置默认输入法
boolean success = Settings.Secure.putString(context.getContentResolver(), key, value);
Log.d("TAG", String.format("writeDbDefaultInputMethod(%s),result: %s", value, success));
}