1. 程式人生 > >安卓原始碼--]Latin輸入法怎麼預設勾選幾種語言

安卓原始碼--]Latin輸入法怎麼預設勾選幾種語言

[SOLUTION] 【GB】 提供簡單的sample code,如預設將俄語、英文、法語輸入法勾選:

1.新增檔案LatinImeReceiver.java

package com.android.inputmethod.latin;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.content.SharedPreferences;

import android.content.SharedPreferences.Editor;

import android.preference.PreferenceManager;

import android.provider.Settings;

import android.util.Log;

import android.view.inputmethod.InputMethodInfo;

import android.view.inputmethod.InputMethodManager;

//import android.view.inputmethod.InputMethodSubtype;

import android.text.TextUtils;

public class LatinImeReceiver extends BroadcastReceiver  

{

    private static final String TAG = LatinImeReceiver.class.getSimpleName();

    @Override

public void onReceive(Context context, Intent intent) {

Log.d("LatinImeReceiver", "step1");

SharedPreferences sp = context.getSharedPreferences("com.android.inputmethod.latin_preferences", Context.MODE_PRIVATE);

boolean hasSet = sp.getBoolean("has_set", false);

    if (!hasSet) {

Log.d("LatinImeReceiver", "step2");

Editor editor = sp.edit();

Log.d("LatinImeReceiver", "step3");

editor.putString(LatinIME.PREF_SELECTED_LANGUAGES, "en_US,ru,fr"); //預設將英語、俄語勾選,具體該怎麼寫可以參考inputlanguageselection.java中的WHITELIST_LANGUAGES

editor.putBoolean("has_set", true);

Log.d("LatinImeReceiver", "step4");

//editor.commit();

SharedPreferencesCompat.apply(editor);

Log.d("LatinImeReceiver", "step5");

}     

   }

將其放置到路徑packages/inputmethods/LatinIME/java/src/com/android/inputmethod/latin資料夾下面

2.註冊intent,在packages/inputmethods/LatinIME/java/androidManifest.xml中增加   

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

許可權

並在最後面加入LatinImeReceiver:  

<receiver android:name="LatinImeReceiver" android:enabled="true">

<intent-filter>

<action android:name="android.intent.action.BOOT_COMPLETED" />

</intent-filter>

</receiver>

3 重新編譯整個工程

【ICS】

1.在mediatek/config/{projectname}/ProjectConfig.mk中修改如下的config,只需要把預設的語言加在後邊即可

    DEFAULT_LATIN_IME_LANGUAGES = en_US hi

DEFAULT_LATIN_IME_LANGUAGES後面的格式需要與packages\inputmethods\LatinIME\java\res\xml\method.xml中的android:imeSubtypeLocale="XXX"字元相匹配,後面新增的語言要與“XXX”相同,例如如果要加印度語言DEFAULT_LATIN_IME_LANGUAGES = en_US hi   中間用空格隔開。這個後面的格式與MTK_PRODUCT_LOCALES不一樣,MTK_PRODUCT_LOCALES後面是系統的語言以及要編譯到系統中的資源的配置。

2.在LatinIMEReceiver.java中  setDefaultSubtypes函式中增加紅色部分

   private void setDefaultSubtypes(Context context) {

        final String serviceName = "com.android.inputmethod.latin/.LatinIME";

        final String currentPackageName = "com.android.inputmethod.latin";

        final String enable = Settings.Secure.getString(context.getContentResolver(),

                Settings.Secure.ENABLED_INPUT_METHODS);

        final InputMethodManager imm = (InputMethodManager) context.getSystemService(

                Context.INPUT_METHOD_SERVICE);

        final StringBuilder builder = new StringBuilder();

        // Get sub type hash code

        for (InputMethodInfo info : imm.getInputMethodList()) {

            if (currentPackageName.equals(info.getPackageName())) {

                for (int i = 0; i < info.getSubtypeCount(); i++) {

                    final InputMethodSubtype subtype = info.getSubtypeAt(i);

                    final String locale = subtype.getLocale().toString();

                    if (isDefaultLocale(locale)) {

                        Log.i(TAG, "default enabled subtype locale = " + locale);

                        builder.append(';');

                        builder.append(subtype.hashCode());

                    }

                }

                break;

            }

        }

        // Insert the sub type

        if (builder.length() > 0 && !TextUtils.isEmpty(enable)) {

            final String subtype = builder.toString();

            builder.setLength(0);

            final int index = enable.indexOf(serviceName) + serviceName.length();

            if (enable.length() > index) {

                builder.append(enable.substring(0, index));

                builder.append(subtype);

                builder.append(enable.substring(index));

            } else if (enable.length() == index) {

                builder.append(enable);

                builder.append(subtype);

            } else {

                return;

            }

        } else {

            Log.w(TAG, "Build Latin IME subtype failed: " + " builder length = " + builder.length()

                    + "; enable isEmpty :" + TextUtils.isEmpty(enable));

            return;

        }

        // Commit the result

        android.provider.Settings.Secure.putString(context.getContentResolver(),

                android.provider.Settings.Secure.ENABLED_INPUT_METHODS, builder.toString());

       String lastInputMethodId = Settings.Secure.getString(context

  .getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);

Log.w(TAG, "DEFAULT_INPUT_METHOD = " +  lastInputMethodId);

if(lastInputMethodId.equals(serviceName)) {

Log.w(TAG, "DEFAULT_INPUT_METHOD = com.android.inputmethod.latin/.LatinIME" );

for (InputMethodInfo info : imm.getInputMethodList()) {

if (currentPackageName.equals(info.getPackageName())) {

for (int i = 0; i < info.getSubtypeCount(); i++) {

final InputMethodSubtype subtype = info.getSubtypeAt(i);

final String[] locales = IMEFeatureOption.DEFAULT_LATIN_IME_LANGUAGES;

Log.w(TAG, "i = " + i + ", locales[0] = " + locales[0]);

if((subtype.getLocale()).equals(locales[0])) {

Log.w(TAG, "putString   " +  subtype.hashCode());

android.provider.Settings.Secure.putInt(context.getContentResolver(),

android.provider.Settings.Secure.SELECTED_INPUT_METHOD_SUBTYPE, subtype.hashCode());

}

}

break;

}

}

}

    }

【JB、KK】

JB中DEFAULT_LATIN_IME_LANGUAGES config沒有用到,沒有LatinIMEReceiver.java這個檔案。所以要預設勾選多種語言需要參照ICS的做法增加以下部分:

比如預設選中泰語和英語:

1.增加LatinImeReceiver.java檔案放在packages\inputmethods\LatinIME\java\src\com\android\inputmethod\latin目錄下

package com.android.inputmethod.latin;

import com.mediatek.common.featureoption.IMEFeatureOption;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.content.SharedPreferences;

import android.provider.Settings;

import android.util.Log;

import android.view.inputmethod.InputMethodInfo;

import android.view.inputmethod.InputMethodManager;

import android.view.inputmethod.InputMethodSubtype;

import android.text.TextUtils;

public class LatinImeReceiver extends BroadcastReceiver {

private static final String TAG = LatinImeReceiver.class.getSimpleName();

   @Override

public void onReceive(Context context, Intent intent) {

// Set the default input language at the system boot completed.

if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {

SharedPreferences sp = context.getSharedPreferences("default_input_language_config",

Context.MODE_PRIVATE);

boolean hasSet = sp.getBoolean("has_set", false);

if (!hasSet) {

setDefaultSubtypes(context);

sp.edit().putBoolean("has_set", true).commit();

}

}

}

/**

* M: Set the default IME subtype.

*/

private void setDefaultSubtypes(Context context) {

final String serviceName = "com.android.inputmethod.latin/.LatinIME";

final String currentPackageName = "com.android.inputmethod.latin";

final String enable = Settings.Secure.getString(context.getContentResolver(),

Settings.Secure.ENABLED_INPUT_METHODS);

final InputMethodManager imm = (InputMethodManager) context.getSystemService(

Context.INPUT_METHOD_SERVICE);

final StringBuilder builder = new StringBuilder();

// Get sub type hash code

for (InputMethodInfo info : imm.getInputMethodList()) {

if (currentPackageName.equals(info.getPackageName())) {

for (int i = 0; i < info.getSubtypeCount(); i++) {

final InputMethodSubtype subtype = info.getSubtypeAt(i);

final String locale = subtype.getLocale().toString();

if (isDefaultLocale(locale)) {

Log.i(TAG, "default enabled subtype locale = " + locale);

builder.append(';');

builder.append(subtype.hashCode());

}

}

break;

}

}

// Insert the sub type

if (builder.length() > 0 && !TextUtils.isEmpty(enable)) {

final String subtype = builder.toString();

           builder.setLength(0);

final int index = enable.indexOf(serviceName) + serviceName.length();

if (enable.length() > index) {

builder.append(enable.substring(0, index));

builder.append(subtype);

builder.append(enable.substring(index));

} else if (enable.length() == index) {

builder.append(enable);

builder.append(subtype);

} else {

return;

}

    } else {

Log.w(TAG, "Build Latin IME subtype failed: " + " builder length = " + builder.length()

+ "; enable isEmpty :" + TextUtils.isEmpty(enable));

return;

}

// Commit the result

android.provider.Settings.Secure.putString(context.getContentResolver(),

android.provider.Settings.Secure.ENABLED_INPUT_METHODS, builder.toString());

String lastInputMethodId = Settings.Secure.getString(context

  .getContentResolver(), Settings.Secure.DEFAULT_INPUT_METHOD);

Log.w(TAG, "DEFAULT_INPUT_METHOD = " +  lastInputMethodId);

if(lastInputMethodId.equals(serviceName)) {

Log.w(TAG, "DEFAULT_INPUT_METHOD = com.android.inputmethod.latin/.LatinIME" );

for (InputMethodInfo info : imm.getInputMethodList()) {

if (currentPackageName.equals(info.getPackageName())) {

for (int i = 0; i < info.getSubtypeCount(); i++) {

final InputMethodSubtype subtype = info.getSubtypeAt(i);

final String[] locales = IMEFeatureOption.DEFAULT_LATIN_IME_LANGUAGES;

Log.w(TAG, "i = " + i + ", locales[0] = " + locales[0]);

if((subtype.getLocale()).equals(locales[0])) {

Log.w(TAG, "putString   " +  subtype.hashCode());

android.provider.Settings.Secure.putInt(context.getContentResolver(),

android.provider.Settings.Secure.SELECTED_INPUT_METHOD_SUBTYPE, subtype.hashCode());

}

}

break;

}

}

}

}

/**

* M: Check if the current locale is default or not.

*/

private boolean isDefaultLocale (String locale) {

final String[] locales = IMEFeatureOption.DEFAULT_LATIN_IME_LANGUAGES;

for (String s : locales) {

if (s.equals(locale)) {

return true;

}

}

return false;

}

}

2.修改packages/inputmethods/latinime/java/androidmanifest.xml檔案,在此檔案中增加LatinImeReceiver的申明,      

<receiver android:name="LatinImeReceiver" android:enabled="true">

<intent-filter>

<action android:name="android.intent.action.BOOT_COMPLETED" />

      </intent-filter>

</receiver>

並增加下面3個許可權

<uses-permission android:name="android.permission.WRITE_SETTINGS" />

<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

改動如下:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

        coreApp="true"

        package="com.android.inputmethod.latin">

    <uses-permission android:name="android.permission.VIBRATE"/>

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <uses-permission android:name="android.permission.READ_USER_DICTIONARY" />

    <uses-permission android:name="android.permission.READ_CONTACTS" />

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<uses-permission android:name="android.permission.WRITE_SETTINGS" />

<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />

    <application android:label="@string/aosp_android_keyboard_ime_name"

            android:icon="@drawable/ic_ime_settings"

            android:backupAgent="BackupAgent"

            android:killAfterRestore="false">

        <service android:name="LatinIME"

                android:label="@string/aosp_android_keyboard_ime_name"

                android:permission="android.permission.BIND_INPUT_METHOD">

            <intent-filter>

                <action android:name="android.view.InputMethod" />

            </intent-filter>

            <meta-data android:name="android.view.im" android:resource="@xml/method" />

        </service>

        <service android:name=".spellcheck.AndroidSpellCheckerService"

                 android:label="@string/spell_checker_service_name"

                 android:permission="android.permission.BIND_TEXT_SERVICE">

            <intent-filter>

                <action android:name="android.service.textservice.SpellCheckerService" />

            </intent-filter>

            <meta-data android:name="android.view.textservice.scs" android:resource="@xml/spellchecker" />

        </service>

        <activity android:name="SettingsActivity" android:label="@string/english_ime_settings"

                  android:uiOptions="splitActionBarWhenNarrow">

            <intent-filter>

                <action android:name="android.intent.action.MAIN"/>

            </intent-filter>

        </activity>

        <activity android:name="com.android.inputmethod.latin.spellcheck.SpellCheckerSettingsActivity"

                  android:label="@string/android_spell_checker_settings">

            <intent-filter>

                <action android:name="android.intent.action.MAIN"/>

            </intent-filter>

        </activity>

        <activity android:name="DebugSettingsActivity" android:label="@string/english_ime_debug_settings">

            <intent-filter>

                <action android:name="android.intent.action.MAIN"/>

            </intent-filter>

        </activity>

        <receiver android:name="SuggestionSpanPickedNotificationReceiver" android:enabled="true">

            <intent-filter>

                <action android:name="android.text.style.SUGGESTION_PICKED" />

            </intent-filter>

        </receiver>

<receiver android:name="LatinImeReceiver" android:enabled="true">

<intent-filter>

<action android:name="android.intent.action.BOOT_COMPLETED" />

</intent-filter>

</receiver>

    </application>

</manifest>

3. 還需要在packages/inputmethods/latinime/java/Android.mk檔案當中加入LOCAL_JAVA_LIBRARIES := mediatek-common才能編譯通過;

4. 在packages\apps\Settings\src\com\android\settings\inputmethod\InputMethodAndSubtypeUtil.java文件中的updateSubtypesPreferenceChecked函式中把break改為continue。

5.在mediatek/config/{projectname}/ProjectConfig.mk中修改如下的config,只需要把預設的語言寫在在後邊即可

    DEFAULT_LATIN_IME_LANGUAGES = hi en_US 其中第一個語言即為預設的輸入語言

DEFAULT_LATIN_IME_LANGUAGES後面的格式需要與packages\inputmethods\LatinIME\java\res\xml\method.xml中的android:imeSubtypeLocale="XXX"字元相匹配,後面新增的語言要與“XXX”相同,例如如果要加印度語言DEFAULT_LATIN_IME_LANGUAGES = en_US hi   中間用空格隔開。這個後面的格式與MTK_PRODUCT_LOCALES不一樣,MTK_PRODUCT_LOCALES後面是系統的語言以及要編譯到系統中的資源的配置。

6.KK的版本還需要增加以下修改:

修改Latin\java的Android.mk,增加LOCAL_PRIVILEGED_MODULE := true

再重新new整個工程,燒機後就可以看到效果。謝謝

 【L版本】

(1)新增加一個LatinImeRe.java檔案

放在packages\inputmethods\LatinIME\java\src\com\android\inputmethod\latin目錄下

檔案內容如下:
package com.android.inputmethod.latin;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.provider.Settings;
import android.util.Log;
import android.view.inputmethod.InputMethodInfo;
import android.view.inputmethod.InputMethodManager;
import android.view.inputmethod.InputMethodSubtype;

import android.text.TextUtils;

public class LatinImeRe extends BroadcastReceiver {

      private static final String TAG = "LatinImeRe";

    @Override
    public void onReceive(Context context, Intent intent) {
        // Set the default input language at the system boot completed.
        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
   Log.w(TAG, "onReceive");
            SharedPreferences sp = context.getSharedPreferences("default_input_language_config",
                    Context.MODE_PRIVATE);
            boolean hasSet = sp.getBoolean("has_set", false);
                   
                setDefaultSubtypes(context);
sp.edit().putBoolean("has_set", true).commit();
        }
    }

    /**
     * M: Set the default IME subtype.
     */
    private void setDefaultSubtypes(Context context) {
        final String serviceName = "com.android.inputmethod.latin/.LatinIME";
        final String currentPackageName = "com.android.inputmethod.latin";
        final String enable = Settings.Secure.getString(context.getContentResolver(),
                Settings.Secure.ENABLED_INPUT_METHODS);
             
       Log.w(TAG, "setDefaultSubtypes() enable :" + enable);
       
        final InputMethodManager imm = (InputMethodManager) context.getSystemService(
                Context.INPUT_METHOD_SERVICE);
        final StringBuilder builder = new StringBuilder();

        // Get sub type hash code
        for (InputMethodInfo info : imm.getInputMethodList()) {
            if (currentPackageName.equals(info.getPackageName())) {
                for (int i = 0; i < info.getSubtypeCount(); i++) {
                    final InputMethodSubtype subtype = info.getSubtypeAt(i);
                    final String locale = subtype.getLocale().toString();
                                        //winny
                     Log.w(TAG, "subtype.getLocale().toString :" + locale);
                     
                    if (isDefaultLocale(locale)) { 
                        Log.i(TAG, "default enabled subtype locale = " + locale);
                        builder.append(';');
                        builder.append(subtype.hashCode());
                    }
                }

                break;
            }
        }
                   
                     Log.w(TAG, "after for loop :" + builder.toString());
        // Insert the sub type
        if (builder.length() > 0) {
            final String subtype = builder.toString();
            builder.setLength(0);

            final int index = enable.indexOf(serviceName) + serviceName.length();
            if (enable.length() > index) {
                builder.append(enable.substring(0, index));
                builder.append(subtype);
                builder.append(enable.substring(index));
            } else if (enable.length() == index) {
                builder.append(enable);
                builder.append(subtype);
            } else {
                return;
            }
        }

        // Commit the result
        android.provider.Settings.Secure.putString(context.getContentResolver(),
                android.provider.Settings.Secure.ENABLED_INPUT_METHODS, builder.toString());
    }

    /**
     * M: Check if the current locale is default or not.
     */
    private boolean isDefaultLocale (String locale) {
    
    String[] locales= new String[]{"th","fr"};  
      //將預設的語言在此新增,注意寫法與method.xml中的subtype語言保持一致,這裡th和fr是泰語和法語的示例。
        for (String s : locales) {
            if (s.equals(locale)) {
                return true;
            }
        }

        return false;

    }
}

(2)修改packages/inputmethods/latinime/java/androidmanifest.xml檔案,在此檔案中增加LatinImeRe的申明

 <receiver android:name="LatinImeRe" android:enabled="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>


並增加下面2個許可權
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
      <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />

(3)在packages/inputmethods/latinime/java/android.xml中修改LOCAL_CERTIFICATE := platform,增加LOCAL_PRIVILEGED_MODULE := true ,之後make new編譯整個工程。