图像键盘支持

用户通常希望使用表情符号、贴纸和其他富媒体内容进行交流。在早期 Android 版本中,软键盘(也称为输入法编辑器,简称 IME)只能向应用发送 Unicode 表情符号。对于富媒体内容,应用会构建应用特有的 API,这些 API 无法在其他应用中使用,或者使用诸如通过简单分享操作或剪贴板发送图像之类的变通方法。

An image showing a keyboard that support image search
图 1. 图像键盘支持示例。

从 Android 7.1(API 级别 25)开始,Android SDK 包含 Commit Content API,它为 IME 提供了一种通用方式,可将图像和其他富媒体内容直接发送到应用中的文本编辑器。该 API 也可在 v13 Support Library 的 25.0.0 版本及更高版本中使用。我们建议使用 Support Library,因为它包含简化实现的辅助方法。

使用此 API,您可以构建接受任何键盘发送的富媒体内容的消息应用,以及可以向任何应用发送富媒体内容的键盘。如图 1 所示,Google 键盘Messages by Google 等应用在 Android 7.1 中支持 Commit Content API。

本文档介绍了如何在 IME 和应用中实现 Commit Content API。

工作原理

键盘图像插入需要 IME 和应用的共同参与。以下顺序描述了图像插入过程中的每个步骤:

  1. 当用户轻触 EditText 时,编辑器会在 EditorInfo.contentMimeTypes 中发送它接受的 MIME 内容类型列表。

  2. IME 读取受支持的类型列表,并在软键盘中显示编辑器可以接受的内容。

  3. 当用户选择图像时,IME 调用 commitContent() 并将 InputContentInfo 发送到编辑器。commitContent() 调用类似于 commitText() 调用,但用于富媒体内容。InputContentInfo 包含一个 URI,该 URI 标识内容提供程序中的内容。

图 2 描述了此过程

An image showing the sequence from Application to IME and back to Application
图 2. 应用到 IME 再到应用的流程。

向应用添加图像支持

要接受来自 IME 的富媒体内容,应用必须告知 IME 它接受哪些内容类型,并指定在接收到内容时执行的回调方法。以下示例演示了如何创建一个接受 PNG 图像的 EditText

Kotlin

var editText: EditText = object : EditText(this) {
    override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection {
        var ic = super.onCreateInputConnection(outAttrs)
        EditorInfoCompat.setContentMimeTypes(outAttrs, arrayOf("image/png"))
        val mimeTypes = ViewCompat.getOnReceiveContentMimeTypes(this)
        if (mimeTypes != null) {
            EditorInfoCompat.setContentMimeTypes(outAttrs, mimeTypes)
            ic = InputConnectionCompat.createWrapper(this, ic, outAttrs)
        }
        return ic
    }
}

Java

EditText editText = new EditText(this) {
    @Override
    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
        InputConnection ic = super.onCreateInputConnection(outAttrs);
        EditorInfoCompat.setContentMimeTypes(outAttrs, new String[]{"image/png"});
        String[] mimeTypes = ViewCompat.getOnReceiveContentMimeTypes(this);
        if (mimeTypes != null) {
            EditorInfoCompat.setContentMimeTypes(outAttrs, mimeTypes);
            ic = InputConnectionCompat.createWrapper(this, ic, outAttrs);
        }
        return ic;
    }
};

以下是进一步解释

以下是推荐的做法:

  • 不支持富媒体内容的编辑器不调用 setContentMimeTypes(),并且将其 EditorInfo.contentMimeTypes 设置为 null

  • 如果 InputContentInfo 中指定的 MIME 类型与它们接受的任何类型都不匹配,编辑器会忽略该内容。

  • 富媒体内容不影响文本光标的位置,也不受其影响。编辑器在处理内容时可以忽略光标位置。

  • 在编辑器的 OnCommitContentListener.onCommitContent() 方法中,即使在加载内容之前,您也可以异步返回 true

  • 与文本不同,富媒体内容提交时会立即生效,而文本可以在 IME 中编辑后再提交。如果您想让用户编辑或删除内容,请自行实现相应逻辑。

要测试您的应用,请确保您的设备或模拟器上有一个可以发送富媒体内容的键盘。您可以在 Android 7.1 或更高版本中使用 Google 键盘。

向 IME 添加图像支持

想要向应用发送富媒体内容的 IME 必须实现 Commit Content API,如下例所示:

  • 覆盖 onStartInput()onStartInputView(),并从目标编辑器读取支持的内容类型列表。以下代码片段展示了如何检查目标编辑器是否接受 GIF 图像。

Kotlin

override fun onStartInputView(editorInfo: EditorInfo, restarting: Boolean) {
    val mimeTypes: Array<String> = EditorInfoCompat.getContentMimeTypes(editorInfo)

    val gifSupported: Boolean = mimeTypes.any {
        ClipDescription.compareMimeTypes(it, "image/gif")
    }

    if (gifSupported) {
        // The target editor supports GIFs. Enable the corresponding content.
    } else {
        // The target editor doesn't support GIFs. Disable the corresponding
        // content.
    }
}

Java

@Override
public void onStartInputView(EditorInfo info, boolean restarting) {
    String[] mimeTypes = EditorInfoCompat.getContentMimeTypes(editorInfo);

    boolean gifSupported = false;
    for (String mimeType : mimeTypes) {
        if (ClipDescription.compareMimeTypes(mimeType, "image/gif")) {
            gifSupported = true;
        }
    }

    if (gifSupported) {
        // The target editor supports GIFs. Enable the corresponding content.
    } else {
        // The target editor doesn't support GIFs. Disable the corresponding
        // content.
    }
}
  • 用户选择图像后,将内容提交到应用。避免在有正在编辑的文本时调用 commitContent(),因为这可能会导致编辑器失去焦点。以下代码片段展示了如何提交 GIF 图像。

Kotlin

// Commits a GIF image.

// @param contentUri = Content URI of the GIF image to be sent.
// @param imageDescription = Description of the GIF image to be sent.

fun commitGifImage(contentUri: Uri, imageDescription: String) {
    val inputContentInfo = InputContentInfoCompat(
            contentUri,
            ClipDescription(imageDescription, arrayOf("image/gif")),
            null
    )
    val inputConnection = currentInputConnection
    val editorInfo = currentInputEditorInfo
    var flags = 0
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
        flags = flags or InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION
    }
    InputConnectionCompat.commitContent(inputConnection, editorInfo, inputContentInfo, flags, null)
}

Java

// Commits a GIF image.

// @param contentUri = Content URI of the GIF image to be sent.
// @param imageDescription = Description of the GIF image to be sent.

public static void commitGifImage(Uri contentUri, String imageDescription) {
    InputContentInfoCompat inputContentInfo = new InputContentInfoCompat(
            contentUri,
            new ClipDescription(imageDescription, new String[]{"image/gif"}),
            null
    );
    InputConnection inputConnection = getCurrentInputConnection();
    EditorInfo editorInfo = getCurrentInputEditorInfo();
    Int flags = 0;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
        flags |= InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION;
    }
    InputConnectionCompat.commitContent(
            inputConnection, editorInfo, inputContentInfo, flags, null);
}

作为 IME 作者,您很可能需要实现自己的内容提供程序来响应内容 URI 请求。例外情况是您的 IME 支持来自现有内容提供程序(如 MediaStore)的内容。有关构建内容提供程序的信息,请参阅内容提供程序文件提供程序文档。

如果您正在构建自己的内容提供程序,建议您不要通过将 android:exported 设置为 false 来导出它。相反,通过将 android:grantUriPermission 设置为 true 来启用提供程序中的权限授予。然后,您的 IME 可以在提交内容时授予访问内容 URI 的权限。有两种方法可以实现这一点:

  • 在 Android 7.1(API 级别 25)及更高版本上,调用 commitContent() 时,将标志参数设置为 INPUT_CONTENT_GRANT_READ_URI_PERMISSION。然后,应用接收到的 InputContentInfo 对象可以通过调用 requestPermission()releasePermission() 来请求和释放临时读取权限。

  • 在 Android 7.0(API 级别 24)及更低版本上,INPUT_CONTENT_GRANT_READ_URI_PERMISSION 会被忽略,因此需要手动授予内容权限。一种方法是使用 grantUriPermission(),但您可以实现满足您自己要求的机制。

要测试您的 IME,请确保您的设备或模拟器上有一个可以接收富媒体内容的应用。您可以在 Android 7.1 或更高版本中使用 Google Messenger 应用。