且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-10-21 14:31:40

DefaultAssistPreference 使用 AssistUtils 来检索当前的Assist。您可以通过反射使用相同的方法:

The DefaultAssistPreference uses an hidden method of AssistUtils to retrieve the current Assist. You can use the same method using reflection:

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;
}

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

If you don't want to use reflection you can directly check the system settings:

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

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

    return null;
}

与读取 AssistUtils相同的设置,但 AssistUtils 也具有后备(如果设置无效)。

It is the same setting that reads AssistUtils, but AssistUtils has also a fallback if the setting is not valid.