使用Google Docs打开PDF文件对用户体验来说并不是一个好主意,速度非常慢且反应迟钝。
API 21之后的解决方案
从API 21开始,我们可以使用PdfRenderer将PDF转换为位图。我从未使用过它,但似乎相当容易。
适用于任何API级别的解决方案
另一种解决方案是下载PDF文档,并通过Intent传递给专门的PDF应用程序进行显示。快速且良好的用户体验,特别是如果此功能不是您的应用程序的核心所在。
使用以下代码下载并打开PDF文档:
public class PdfOpenHelper {
public static void openPdfFromUrl(final String pdfUrl, final Activity activity){
Observable.fromCallable(new Callable<File>() {
@Override
public File call() throws Exception {
try{
URL url = new URL(pdfUrl);
URLConnection connection = url.openConnection();
connection.connect();
InputStream input = new BufferedInputStream(connection.getInputStream());
File dir = new File(activity.getFilesDir(), "/shared_pdf");
dir.mkdir();
File file = new File(dir, "temp.pdf");
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
return file;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<File>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(File file) {
String authority = activity.getApplicationContext().getPackageName() + ".fileprovider";
Uri uriToFile = FileProvider.getUriForFile(activity, authority, file);
Intent shareIntent = new Intent(Intent.ACTION_VIEW);
shareIntent.setDataAndType(uriToFile, "application/pdf");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (shareIntent.resolveActivity(activity.getPackageManager()) != null) {
activity.startActivity(shareIntent);
}
}
});
}
}
要使Intent正常工作,您需要创建一个FileProvider来授予接收应用程序打开文件的许可。
以下是实现方法:
在您的清单文件中:
<provider
android:name="android.support.v4.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>
最后在资源文件夹中创建一个file_paths.xml文件
<?xml version="1.0" encoding="utf-8"?>
<paths>
<files-path name="shared_pdf" path="shared_pdf"/>
</paths>
希望这能有所帮助 =)
您已达到查看或下载非谷歌文档格式文件的带宽限制......
。看起来不太可靠。 - Shobhit Puri