将 uri 发送到文本编辑器应用程序并保存

Send uri to text editor app and have it save

从概念上讲,我想要做的是将资源 uri(引用我的内容提供商 (CP))从我的应用程序 (A) 发送到文本编辑器应用程序 (B)(用户选择),这样文本编辑器将 uri 作为文本流访问,并能够编辑和保存文件。从文本编辑器 (B) 返回一些通知是可取的,但我可以使用 CP 来了解 "writes" 例如。

意图和 CP 是否支持这种级别的交互?

基本上,我不想在我的应用程序中编写自己的文本编辑器 - 我的应用程序管理数据(通过内容提供程序)并且文本编辑器进行操作。

也许将数据发送到临时外部存储位置并将文件路径发送到编辑器 - 但这似乎比需要的更复杂。

好吧,我最终使用了 FileProvider class 并浏览了生成以下代码的支持文档。不完全是我最初打算做的,但从概念上讲结果是相同的(用户按下按钮 - 编辑 file/saves - 用户 returns 返回应用程序):

(在AndroidManifest.xml>

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="my.package.name.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />
    </provider>

并在 res/xml/file_paths.xml:

<?xml version="1.0" encoding="utf-8"?>
    <paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path name="notes" path="notes/"/>
</paths>

并在按钮侦听器中(用户希望 see/edit 他们的笔记):

private class AddNoteListener implements View.OnClickListener {

    @Override
    public void onClick(View v) {
        File notesPath = new File(context.getFilesDir(), "notes");
        if (notesPath.exists() == false) {
            notesPath.mkdir();
        }
        File newFile = new File(notesPath, "my_note.txt");
        try {
            if (newFile.exists() == false) {
                newFile.createNewFile();
            }
            Uri contentUri = FileProvider.getUriForFile(context, "my.package.name.fileprovider", newFile);
            Intent intent = new Intent(Intent.ACTION_EDIT);
            intent.setDataAndType(contentUri, "text/plain");
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

            List<ResolveInfo> resInfoList = context.getPackageManager().queryIntentActivities(intent,  PackageManager.MATCH_DEFAULT_ONLY);
            for (ResolveInfo resolveInfo : resInfoList) {
                String packageName = resolveInfo.activityInfo.packageName;
                context.grantUriPermission(packageName, contentUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }
            context.startActivity(Intent.createChooser(intent,"Title"));
        } catch (IOException ioe) {
            e.printStackTrace();
        }
    }
}

参考文献:

Granting permissions
Proper mime type
FileProvider