如何通过代码获取android中的默认设备辅助应用程序?

Jam*_*ame 1 android google-voice android-intent android-settings android-6.0-marshmallow

我的手机安装了两个语音搜索:谷歌应用程序和S语音应用程序.默认应用程序是S-voice app,如下图所示.我的问题是,如何在Android 6.0中使用编程方式获取默认语音应用程序.先感谢您

在此输入图像描述

这就是我做的

private boolean isMyAppLauncherDefault(String myPackageName) {
    final IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
    filter.addCategory(Intent.CATEGORY_HOME);

    List<IntentFilter> filters = new ArrayList<IntentFilter>();
    filters.add(filter);
    List<ComponentName> activities = new ArrayList<ComponentName>();
    final PackageManager packageManager = (PackageManager) getPackageManager();

    packageManager.getPreferredActivities(filters, activities, null);
    for (ComponentName activity : activities) {

        Log.d(TAG,"======packet default:==="+activity.getPackageName());
    }
    for (ComponentName activity : activities) {

        if (myPackageName.equals(activity.getPackageName())) {
            return true;
        }
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

当我输入时,上面的函数总是返回true com.samsung.voiceserviceplatform.在另一方面,默认应用程序始终返回com.google.android.googlequicksearchbox(表示谷歌语音)

Mat*_*ini 5

DefaultAssistPreference使用的隐藏方法AssistUtils来检索当前协助.您可以使用反射使用相同的方法:

public ComponentName getCurrentAssistWithReflection(Context context) {
    try {
        Method myUserIdMethod = UserHandle.class.getDeclaredMethod("myUserId");
        myUserIdMethod.setAccessible(true);
        Integer userId = (Integer) myUserIdMethod.invoke(null);

        if (userId != null) {
            Constructor constructor = Class.forName("com.android.internal.app.AssistUtils").getConstructor(Context.class);
            Object assistUtils = constructor.newInstance(context);

            Method getAssistComponentForUserMethod = assistUtils.getClass().getDeclaredMethod("getAssistComponentForUser", int.class);
            getAssistComponentForUserMethod.setAccessible(true);
            return (ComponentName) getAssistComponentForUserMethod.invoke(assistUtils, userId);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
Run Code Online (Sandbox Code Playgroud)

如果您不想使用反射,可以直接检查系统设置:

public ComponentName getCurrentAssist(Context context) {
    final String setting = Settings.Secure.getString(context.getContentResolver(), "assistant");

    if (setting != null) {
        return ComponentName.unflattenFromString(setting);
    }

    return null;
}
Run Code Online (Sandbox Code Playgroud)

它与读取的设置相同AssistUtils,但如果设置无效,AssistUtils则还具有后备.