我正在开发API 27中的应用程序,我在从资产文件夹打开PDF时遇到问题。我尝试了很多不同的方法,但仍然没有成功。
PDF打开时,会出现一个空白的黑屏。我在其返回的所有步骤中检查了file.exist() return false
'false'。
我真的需要有关此主题的帮助。另外,我尝试了内部和外部存储。还尝试了不同的意图标签。但仍然没有运气。
这是我用过的功能。
private void openPDFFiles(String fileName) //fileName is the pdf file name which is keep in assets folder. ex file.pdf
{
AssetManager assetManager = getApplicationContext().getAssets();
InputStream in = null;
OutputStream out = null;
File imagePath = new File(getFilesDir(), "Videos");
File file = new File(imagePath, "1.pdf");
try {
in = assetManager.open(fileName);
out = openFileOutput(file.getName(), MODE_PRIVATE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
System.out.println(e);
}
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(FileProvider.getUriForFile(getApplicationContext(), "com.administrator.siemens.android.fileprovider", file), "application/pdf");
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
} catch (RuntimeException ex) {
Toast.makeText(Document.this, "There's no PDF Reader found in your device", Toast.LENGTH_SHORT).show();
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
System.out.println("1222222222");
}
的manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.administrator.siemens">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@drawable/me"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.administrator.siemens.android.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepath" />
</provider>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
filepath.xml:
<paths>
<files-path name="my_docs" path="Videos/"/>
</paths>
非常感谢!如果有人能帮助我的话。