简体   繁体   English

如何从 Assets 文件夹中共享 PDF

[英]How to Share PDF from Assets Folder

I am developing a book application.我正在开发一个图书应用程序。 A professional application which I later publish on play store.我后来在 Play Store 上发布的专业应用程序。 It would be nice if it had a share button which shares pdf to different apps.如果它有一个分享按钮,将 pdf 分享给不同的应用程序,那就太好了。 I spent hours searching for that but I couldn't found the way to share pdf that is in Assets folder.我花了几个小时寻找它,但我找不到共享 Assets 文件夹中的 pdf 的方法。 Most of them are sharing images and those who are sharing pdf are using URL.他们中的大多数是共享图像,而那些共享 pdf 的人正在使用 URL。 It would be nice if anyone tells me.如果有人告诉我,那就太好了。 Thanks in advance.提前致谢。

Here is the code I wrote a code in java language.这是我用 java 语言编写的代码。 I translated it from a fellow member who have written in Kotlin language.我是从一位用 Kotlin 语言编写的成员那里翻译的。

In AndroidManifest.xml add the following lines just before在 AndroidManifest.xml 之前添加以下行

<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
    android:name="android.support.FILE_PROVIDER_PATHS"
    android:resource="@xml/file_path" />
</provider>

After that create an xml resource file name file_path.之后创建一个 xml 资源文件名 file_path。 Then copy the below code there.然后将下面的代码复制到那里。

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

Then go in that java class where you are doing sharing.然后 go 在 java class 中进行共享。 There we create new functions.在那里我们创建了新的函数。 These actually create an empty file in files directory, then copy the content of asset to file and create a share intent then.这些实际上是在 files 目录中创建一个空文件,然后将资产的内容复制到文件并创建共享意图。

private File createFileInFilesDir(String filename) throws IOException {
    File file = new File(getFilesDir().getPath()+"/"+filename);
    if (file.exists()) {
        if (!file.delete()) {
            throw new IOException();
        }
    }
    if (!file.createNewFile()) {
        throw new IOException();
    }
    return file;
}
private void copyAssetToFile(String assetName, File file) throws IOException {
    byte[] buffer = new byte[1024];
    InputStream inputStream = getAssets().open(assetName);
    OutputStream outputStream = new FileOutputStream(file);
    while (inputStream.read(buffer) > 0) {
        outputStream.write(buffer);
    }
}
private Intent createIntentForFile(File file, String intentAction) {
    Uri uri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider", file);
    Intent intent = new Intent(intentAction);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    intent.setDataAndType(uri, "application/pdf");
    intent.putExtra(Intent.EXTRA_STREAM,uri);
    return intent;
}
private void sharePdfAsset(String assetName, String intentAction) throws IOException {
    try {
        File file = createFileInFilesDir(assetName);
        copyAssetToFile(assetName, file);
        Intent intent = createIntentForFile(file, intentAction);

        startActivity(Intent.createChooser(intent, "Sharing PDF"));
    } catch (IOException e) {
        e.printStackTrace();
        new AlertDialog.Builder(this)
                .setTitle(R.string.error)
                .setMessage(R.string.share_error)
                .show();
    }
}

Actually I am using a proper share button to share pdf on action bar so I used onoptionsItemselected method.实际上,我正在使用适当的共享按钮在操作栏上共享 pdf,所以我使用了 onoptionsItemselected 方法。

 public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    // We are using switch case because multiple icons can be kept
    switch (item.getItemId()) {
        case R.id.shareButton:
            try {
                sharePdfAsset("your_file_name.pdf", Intent.ACTION_SEND);
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
    return super.onOptionsItemSelected(item);

If anyone else had done this in easier way please share.如果其他人以更简单的方式做到了这一点,请分享。

The short answer is: copy the file from assets to storage简短的回答是:将文件从资产复制到存储

Then use FileProvider and ACTION_SEND to share the file from storage.然后使用 FileProvider 和 ACTION_SEND 从存储中共享文件。

But more elegant would be to not copy and use an assets provider.但更优雅的是不复制和使用资产提供者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM