安卓如何通过键盘发送图片

6

我正在尝试实现一个键盘应用程序,它应该能够将图像发送到当前活动(Whatsapp、短信应用等)。

有没有方法可以实现这一点?当然,它将被限制在接受图像的应用程序中,但我想知道最佳方法是什么。

尝试使用带有ImageSpan的StringBuilder,但无法使其工作。我想知道是否有更好的方法。也许可以使用意图(Intents)?


你有找到解决方案了吗? - La masse
在之前的 Android 版本中,软键盘(也称为输入法编辑器或 IME)只能向应用程序发送 Unicode 表情符号。对于丰富的内容,应用程序必须构建特定于应用程序的 API,这些 API 不能在其他应用程序中使用,或者使用像通过 Easy Share Action 或剪贴板发送图像这样的解决方法。https://developer.android.com/preview/image-keyboard.html - hector6872
1个回答

3
通过向前台应用程序发送Intents来最终实现了这一点,但这种方法有局限性:聊天应用通常需要选择对话,这会破坏用户流程并增加不必要的步骤(除非它们公开了一种向特定聊天发送Intent的方法)。
可以按以下方式实现:
Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    sendIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    sendIntent.setPackage(getCurrentAppPackage(context, editorInfo));
    return sendIntent;

在绑定到输入字段时,您可以从您的 IME 实现中获取一个 Context 和一个 EditorInfo,其中 getCurrentAppPackage(...) 是一个方法,它返回前台 Activity。

public String getCurrentAppPackage(Context context, EditorInfo info) {
    if(info != null && info.packageName != null) {
        return info.packageName;
    }
    final PackageManager pm = context.getPackageManager();
    //Get the Activity Manager Object
    ActivityManager aManager =
            (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    //Get the list of running Applications
    List<ActivityManager.RunningAppProcessInfo> rapInfoList = aManager.getRunningAppProcesses();
    //Iterate all running apps to get their details
    for (ActivityManager.RunningAppProcessInfo rapInfo : rapInfoList) {
        //error getting package name for this process so move on
        if (rapInfo.pkgList.length == 0) {
            Log.i("DISCARDED PACKAGE", rapInfo.processName);
            continue;
        }
        try {
            PackageInfo pkgInfo = pm.getPackageInfo(rapInfo.pkgList[0], PackageManager.GET_ACTIVITIES);
            return pkgInfo.packageName;
        } catch (PackageManager.NameNotFoundException e) {
            // Keep iterating
        }
    }
    return null;
}

更新:在API级别25中添加了Commit Content API(支持库可使其在API 13上工作)。更多信息请参见:https://developer.android.com/preview/image-keyboard.html。 在应用程序开始实施之前,可以使用以上方法作为备选方案。


嗨Framundo,你能分享一下你的代码吗?显示你是如何分享到前台活动的? 此外,请注意关于提交内容,应用程序必须能够接收丰富的内容,并且由于这是相当新的,没有那么多应用程序具备此功能。所以我认为两个选项必须一起实现。 - Juan Giorello
我同意,编辑了答案以包括示例代码并警告回退到手动方法。 - framundo
@framundo,请发送示例代码,因为我正在开发相同的功能并遇到相同的问题。 - Mr.vicky patel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接