📜  如何在 Android 中实现 PDF 选择器?

📅  最后修改于: 2022-05-13 01:54:49.206000             🧑  作者: Mango

如何在 Android 中实现 PDF 选择器?

在本文中,我们将了解如何在 android studio 中实现 PDF 选择器并获取 pdf 的 Uri 和 Path。在这个应用程序中,我们将获得用户读取外部存储的权限,然后向用户显示所选 PDF 的 Uri 和路径,表明我们已成功选择 PDF。这是我们将在此应用程序中构建的示例视频。请注意,我们将使用Java语言来实现这个应用程序。

分步实施

第 1 步:创建一个新项目

  • 打开一个新项目。
  • 我们将使用Java语言开发 Empty Activity。保持所有其他选项不变。
  • 您可以在方便时更改项目的名称。
  • 将有两个名为 activity_main.xml 和 MainActivity 的默认文件。Java

如果您不知道如何在 Android Studio 中创建新项目,可以参考如何在 Android Studio 中创建/启动新项目?

第二步:添加存储权限

按照路径app > manifests > AndroidManifest.xml并将以下代码粘贴到其中。

第 3 步:处理 XML 文件

导航到app > res > layout > activity_main.xml并将以下代码添加到该文件。下面是activity_main.xml文件的代码。

XML


  
    


Java
package com.example.pdfpicker;
  
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
  
public class MainActivity extends AppCompatActivity {
  
    // Initialize variable
    Button btSelect;
    TextView tvUri, tvPath;
    ActivityResultLauncher resultLauncher;
  
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // assign variable
        btSelect = findViewById(R.id.bt_select);
        tvUri = findViewById(R.id.tv_uri);
        tvPath = findViewById(R.id.tv_path);
  
        // Initialize result launcher
        resultLauncher = registerForActivityResult(
            new ActivityResultContracts
                .StartActivityForResult(),
            new ActivityResultCallback() {
                @Override
                public void onActivityResult(
                    ActivityResult result)
                {
                    // Initialize result data
                    Intent data = result.getData();
                    // check condition
                    if (data != null) {
                        // When data is not equal to empty
                        // Get PDf uri
                        Uri sUri = data.getData();
                        // set Uri on text view
                        tvUri.setText(Html.fromHtml(
                            "PDF Uri
"                             + sUri));                            // Get PDF path                         String sPath = sUri.getPath();                         // Set path on text view                         tvPath.setText(Html.fromHtml(                             "PDF Path
"                             + sPath));                     }                 }             });            // Set click listener on button         btSelect.setOnClickListener(             new View.OnClickListener() {                 @Override public void onClick(View v)                 {                     // check condition                     if (ActivityCompat.checkSelfPermission(                             MainActivity.this,                             Manifest.permission                                 .READ_EXTERNAL_STORAGE)                         != PackageManager                                .PERMISSION_GRANTED) {                         // When permission is not granted                         // Result permission                         ActivityCompat.requestPermissions(                             MainActivity.this,                             new String[] {                                 Manifest.permission                                     .READ_EXTERNAL_STORAGE },                             1);                     }                     else {                         // When permission is granted                         // Create method                         selectPDF();                     }                 }             });     }        private void selectPDF()     {         // Initialize intent         Intent intent             = new Intent(Intent.ACTION_GET_CONTENT);         // set type         intent.setType("application/pdf");         // Launch intent         resultLauncher.launch(intent);     }        @Override     public void onRequestPermissionsResult(         int requestCode, @NonNull String[] permissions,         @NonNull int[] grantResults)     {         super.onRequestPermissionsResult(             requestCode, permissions, grantResults);            // check condition         if (requestCode == 1 && grantResults.length > 0             && grantResults[0]                    == PackageManager.PERMISSION_GRANTED) {             // When permission is granted             // Call method             selectPDF();         }         else {             // When permission is denied             // Display toast             Toast                 .makeText(getApplicationContext(),                           "Permission Denied",                           Toast.LENGTH_SHORT)                 .show();         }     } }


第 4 步:处理Java文件

转到MainActivity。 Java文件并参考以下代码。下面是 MainActivity 的代码。 Java文件。代码内部添加注释以更详细地理解代码

Java

package com.example.pdfpicker;
  
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
  
public class MainActivity extends AppCompatActivity {
  
    // Initialize variable
    Button btSelect;
    TextView tvUri, tvPath;
    ActivityResultLauncher resultLauncher;
  
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // assign variable
        btSelect = findViewById(R.id.bt_select);
        tvUri = findViewById(R.id.tv_uri);
        tvPath = findViewById(R.id.tv_path);
  
        // Initialize result launcher
        resultLauncher = registerForActivityResult(
            new ActivityResultContracts
                .StartActivityForResult(),
            new ActivityResultCallback() {
                @Override
                public void onActivityResult(
                    ActivityResult result)
                {
                    // Initialize result data
                    Intent data = result.getData();
                    // check condition
                    if (data != null) {
                        // When data is not equal to empty
                        // Get PDf uri
                        Uri sUri = data.getData();
                        // set Uri on text view
                        tvUri.setText(Html.fromHtml(
                            "PDF Uri
"                             + sUri));                            // Get PDF path                         String sPath = sUri.getPath();                         // Set path on text view                         tvPath.setText(Html.fromHtml(                             "PDF Path
"                             + sPath));                     }                 }             });            // Set click listener on button         btSelect.setOnClickListener(             new View.OnClickListener() {                 @Override public void onClick(View v)                 {                     // check condition                     if (ActivityCompat.checkSelfPermission(                             MainActivity.this,                             Manifest.permission                                 .READ_EXTERNAL_STORAGE)                         != PackageManager                                .PERMISSION_GRANTED) {                         // When permission is not granted                         // Result permission                         ActivityCompat.requestPermissions(                             MainActivity.this,                             new String[] {                                 Manifest.permission                                     .READ_EXTERNAL_STORAGE },                             1);                     }                     else {                         // When permission is granted                         // Create method                         selectPDF();                     }                 }             });     }        private void selectPDF()     {         // Initialize intent         Intent intent             = new Intent(Intent.ACTION_GET_CONTENT);         // set type         intent.setType("application/pdf");         // Launch intent         resultLauncher.launch(intent);     }        @Override     public void onRequestPermissionsResult(         int requestCode, @NonNull String[] permissions,         @NonNull int[] grantResults)     {         super.onRequestPermissionsResult(             requestCode, permissions, grantResults);            // check condition         if (requestCode == 1 && grantResults.length > 0             && grantResults[0]                    == PackageManager.PERMISSION_GRANTED) {             // When permission is granted             // Call method             selectPDF();         }         else {             // When permission is denied             // Display toast             Toast                 .makeText(getApplicationContext(),                           "Permission Denied",                           Toast.LENGTH_SHORT)                 .show();         }     } }

这是我们应用程序的最终输出。

输出: