[英]Open Local PDF in external Application from Android Studio HTML document
當前正在制作WebView HTML應用程序,並且我指向本地PDF文件的鏈接(路徑是相對的)不起作用。 我只希望它在外部應用程序中打開(而不是在WebView中)。 我已嘗試從此站點嘗試多個PDF意圖,但均未成功。
我最初在public Boolean launchPDF
之上具有Override
,但一直
:method does not override or implement method from a supertype
我需要這是所有PDF的總括聲明,因為我有很多。
AndroidManifest.xml中:
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebSettings;
import android.webkit.WebView;
public class MainActivity extends AppCompatActivity {
private WebView myWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myWebView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
myWebView.loadUrl("file:///android_asset/index.html");
}
public boolean launchPDF(WebView view, String url) {
if (urlIsPDF(url)) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(url), "application/pdf");
try {
view.getContext().startActivity(intent);
} catch (ActivityNotFoundException e) {
//User does not have pdf viewer installed
}
} else {
myWebView.loadUrl(url);
}
return true;
}
public boolean urlIsPDF(String url) {
return url.endsWith(".pdf");
}
};
一種選擇是使用我的StreamProvider
能夠直接從assets/
從您的應用程序提供PDF文件。 設置起來並不難,並且不需要您在運行時復制任何數據。 您將在ACTION_VIEW
Intent
使用StreamProvider
提供的Uri
。 但是,這不適用於所有PDF查看器,尤其是不是Google Drive應用程序中的一部分,除非他們修復了它們的錯誤。
如果需要更大的兼容性,請將資產復制到本地文件系統上的文件中(例如,在getCacheDir()
),然后使用Android支持庫中的FileProvider
。 除了必須進行復制外,這與使用StreamProvider
具有相同的基本效果。 通過文件而不是直接從APK內素材資源提供服務可以改善與PDF查看器的兼容性,盡管由於它們處理content
Uri
值的方式存在錯誤,仍有一些可能會出現問題。
另一個選擇是將某種PDF查看功能嵌入到您的應用程序中。 在此博客文章中 ,我概述了三個選項。 它們都在兼容性和大小方面進行了權衡,沒有一個功能比獨立的PDF查看器更好。
或者,您可以找到一些工具將PDF轉換為HTML / CSS / images,將其打包在您的應用中,然后在WebView
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.