尝试单击按钮从资源文件夹中打开 pdf 文件
public class CodSecreen extends AppCompatActivity {
PDFView pdfView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cod_secreen);
pdfView=(PDFView)findViewById(R.id.pdf);
Intent intent = getIntent();
String str = intent.getStringExtra("message");
if (str.equals(getResources().getString(R.string.introduction))){
pdfView.fromAsset("phpvariable.pdf").load();
}
}
}
Run Code Online (Sandbox Code Playgroud)
通过传递按钮的字符串值
bttn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String str = bttn1.getText().toString();
Intent i=new Intent(DetailSecreen.this,CodSecreen.class);
startActivity(i);
}
});
Run Code Online (Sandbox Code Playgroud)
安卓Q更新
这是一个较旧的问题,但在 Android Q 中,由于新的文件访问权限/系统,出现了一些变化。现在不可能再将 PDF 文件存储在公共文件夹中。cache我通过在应用程序的 data/data 文件夹中创建 PDF 文件的副本解决了这个问题。WRITE_EXTERNAL_STORAGE通过这种方法,不再需要许可。
打开 PDF 文件:
fun openPdf(){
// Open the PDF file from raw folder
val inputStream = resources.openRawResource(R.raw.mypdf)
// Copy the file to the cache folder
inputStream.use { inputStream ->
val file = File(cacheDir, "mypdf.pdf")
FileOutputStream(file).use { output ->
val buffer = ByteArray(4 * 1024) // or other buffer size
var read: Int
while (inputStream.read(buffer).also { read = it } != -1) {
output.write(buffer, 0, read)
}
output.flush()
}
}
val cacheFile = File(cacheDir, "mypdf.pdf")
// Get the URI of the cache file from the FileProvider
val uri = FileProvider.getUriForFile(this, "$packageName.provider", cacheFile)
if (uri != null) {
// Create an intent to open the PDF in a third party app
val pdfViewIntent = Intent(Intent.ACTION_VIEW)
pdfViewIntent.data = uri
pdfViewIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
startActivity(Intent.createChooser(pdfViewIntent, "Choos PDF viewer"))
}
}
Run Code Online (Sandbox Code Playgroud)
内部提供程序配置provider_paths.xml,用于访问您自己的应用程序外部的文件。这允许访问cache文件夹中的所有文件:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<cache-path
name="cache-files"
path="/" />
</paths>
Run Code Online (Sandbox Code Playgroud)
在您的文件中添加文件提供程序配置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/provider_paths" />
</provider>
Run Code Online (Sandbox Code Playgroud)
可以通过仅复制文件一次并检查文件是否已存在并替换它来增强此功能。由于打开 PDF 并不是我的应用程序的重要组成部分,因此我只是将其保存在缓存文件夹中,并在用户每次打开 PDF 时覆盖它。
| 归档时间: |
|
| 查看次数: |
7941 次 |
| 最近记录: |