当前位置: 首页 > article >正文

安卓开发,打开PDF文件

1、把PDF文件复制到raw目录下

(1)新建一个Android Resource Directory

(2)Resource type 改成 raw

(3) 把PDF文件复制到raw目录下

2、activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <Button
      android:id="@+id/button1"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:text="打开PDF"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintTop_toTopOf="parent" />
  </LinearLayout>

3、MainActivity.java

package com.example.openpdf;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class MainActivity extends AppCompatActivity {
    String fileName;
    InputStream inputStream;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button buttonOpenPdf = findViewById(R.id.button1);
        buttonOpenPdf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fileName = "one_one.pdf";
                inputStream = getResources().openRawResource(R.raw.one_one);
                request();
            }
        });
    }
    //检查请求
    private void request(){//权限检查
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {//如果返回值为true,意味着应用尚未获得该权限
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }
        else {
            checkAndSavePdf();
        }
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, 2);
        }
        else {
            openPdfFile();
        }
    }
    //权限请求结果处理
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            //如果用户同意授权访问
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                checkAndSavePdf();
            }
            else {
                Toast.makeText(this, "存储权限被拒绝", Toast.LENGTH_SHORT).show();
            }
        }
        if (requestCode == 2) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openPdfFile();
            } else {
                Toast.makeText(this, "读取外部存储权限被拒绝", Toast.LENGTH_SHORT).show();
            }
        }
    }
    //检查文件是否已经保存
    private void checkAndSavePdf() {//check检查
        File pdfFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS + "/math"),fileName);
        if (!pdfFile.exists()) {savePdf();}
    }
    //保存PDF
    private void savePdf() {
        ContentResolver contentResolver = getContentResolver();
        ContentValues contentValues = new ContentValues();
        // 设置文件名
        contentValues.put(MediaStore.Downloads.DISPLAY_NAME, fileName);
        // 设置文件 MIME 类型
        contentValues.put(MediaStore.Downloads.MIME_TYPE, "application/pdf");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // 设置文件相对路径为 Downloads 目录
            contentValues.put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS+"/math");
        }

        // 插入文件信息到 MediaStore 并获取 Uri
        Uri uri = contentResolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues);
        if (uri != null) {
            try {
                // 打开输出流
                OutputStream outputStream = contentResolver.openOutputStream(uri);
                if (outputStream != null) {
                    byte[] buffer = new byte[1024];
                    int length;
                    // 从输入流读取数据并写入输出流
                    while ((length = inputStream.read(buffer)) > 0) {
                        outputStream.write(buffer, 0, length);
                    }
                    // 关闭输出流
                    outputStream.close();
                    // 关闭输入流
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    //打开PDF
    private void openPdfFile() {
        // 假设 PDF 文件在外部存储的 Downloads 目录下
        File pdfFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS+"/math"),fileName);
        if (pdfFile.exists()) {
            Uri uri;
            // 获取文件的 Uri
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                // 使用 FileProvider 生成 content:// 类型的 Uri
                uri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", pdfFile);
            }
            else {uri = Uri.fromFile(pdfFile);}
            // 创建隐式意图
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(uri, "application/pdf");
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);}
            // 检查是否有应用可以处理该意图
            if (getPackageManager().queryIntentActivities(intent, 0).size() > 0) {startActivity(intent);}
            else {Toast.makeText(this, "没有可用的 PDF 阅读器", Toast.LENGTH_SHORT).show();}
        } else {
            Toast.makeText(this, "PDF 文件不存在", Toast.LENGTH_SHORT).show();
        }
    }

}

4、AndroidManifest.xml

在 AndroidManifest.xml 中添加以下代码:

<!-- 声明写入外部存储的权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- 声明读取外部存储的权限 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

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

AndroidManifest.xml 完整代码:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" >
    <!-- 声明写入外部存储的权限 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <!-- 声明读取外部存储的权限 -->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.OpenPDF"
        tools:targetApi="31" >
        <activity
            android:name=".MainActivity"
            android:exported="true" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>
    </application>

</manifest>

5、创建 file_paths.xml 文件 

在 res/xml 目录下创建 file_paths.xml 文件,内容如下:

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

3、


http://www.kler.cn/a/538946.html

相关文章:

  • 数据结构——【二叉树模版】
  • 深度学习|表示学习|Instance Normalization 全面总结|26
  • 十二、Docker Compose 部署 SpringCloudAlibaba 微服务
  • Git常用命令总结
  • Java 魔法:精准掌控 PDF 合同模板,指定页码与关键字替换签章日期
  • 【Spring】什么是Spring?
  • 【Java基础篇】——第2篇:Java语法基础
  • Python Pandas(6):Pandas JSON
  • 前端VSCode常用插件
  • NIO——网络编程
  • 什么是 HTTP/2 和 HTTP/3?
  • 聚焦 MySQL 优化器:探究 Adaptive Hash Index 与 Query Cache 那些事儿
  • Android开发获取缓存,删除缓存
  • 2月9日QT
  • 车载工具简介 --- VH6501基本配置guideline
  • 知识图谱智能应用系统:数据分析与挖掘技术文档
  • 每日一题洛谷P5733 【深基6.例1】自动修正c++
  • AI 网络安全处理 开源 人工智能+网络安全
  • 深入探究 Go 语言中的 Fx 框架:依赖注入的强大工具
  • UMLS初探
  • 如何修改IDEA的maven远程仓库地址
  • monitorenter /moniterexit
  • Oracle数据连接 Dblink
  • 四次挥手详解
  • PID 算法简介(C语言)
  • Ai无限免费生成高质量ppt教程(deepseek+kimi)