我一直在尝试创建一个将在 WebView 中打开网站的 Android 应用程序。例如,我想打开 Google.com 并导航到一个 pdf 文件。我希望能够在应用程序中打开 pdf,而不是下载并在本地打开它。
我已经在我的代码中实现了 PDFViewer,因此最终我将能够在应用程序内的 PDFViewer 中打开一个 pdf,然后在我完成使用后退按钮后导航回网站,而无需离开应用程序。
在activity_main.xml 文件中,我在Webview 下编写了PDFViewer,这样它就可以在调用它时打开pdf,但现在我只得到一个空白页。我会很感激我能得到的任何帮助!!
下面是我的 MainActivity.java 文件
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import com.github.barteksc.pdfviewer.PDFView;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private WebView mywebView;
PDFView pdfView;
String url;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mywebView = (WebView) this.findViewById(R.id.webView);
WebSettings webSettings= mywebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mywebView.loadUrl("www.google.com");
if (url.endsWith(".pdf")) {
PDFView pdfView = findViewById(R.id.pdfView);
new RetrivePdffromUrl().execute(url);
} else {
mywebView.loadUrl(url);
}
}
class RetrivePdffromUrl extends AsyncTask<String, Void, InputStream> {
@Override
protected InputStream doInBackground(String... strings) {
InputStream inputStream = null;
try {
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
if (urlConnection.getResponseCode() == 200) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
return inputStream;
}
@Override
protected void onPostExecute(InputStream inputStream) {
pdfView.fromStream(inputStream).load();
}
}
@Override
public void onBackPressed() {
if(mywebView.canGoBack()){
mywebView.goBack();
}else{
super.onBackPressed();
}
}
}
这是我的 activity_main.xml 文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<com.github.barteksc.pdfviewer.PDFView
android:id="@+id/pdfView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</WebView>
</RelativeLayout>
我对 Android 开发还很陌生,所以如果能得到任何帮助,我将不胜感激。提前致谢!!!