下载后自动打开PDF
Open PDF Automatically After Downloaded
我有一个 webview 应用程序,它具有 pdf 下载功能,可以从一些不同的网站下载 pdf 文件。我想知道如何在下载后立即打开pdf。我的应用程序中还没有 pdf reader,因为我不知道如何应用它。
我已经阅读了我提出的类似问题的所有答案,但所有答案都不适用。问题是 pdf 的名称是基于上传者设置的,所以 pdf 文件的名称会因访问的网站而异。
下面的代码中,下载的pdf文件生成的名称是根据站点上的pdf名称生成的,不是我定的。
是否可以根据代码打开pdf文件,还是我应该修改代码?
package com.example.app;
public class WebViewActivity extends AppCompatActivity {
String url = "";
NetworkChangeListener networkChangeListener = new NetworkChangeListener();
private boolean multiple_files = true;
private static String file_type = "*/*";
private ValueCallback<Uri> file_data;
private ValueCallback<Uri[]> file_path;
private final static int file_req_code = 1;
private static final String TAG = WebViewActivity.class.getSimpleName();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = findViewById(R.id.webView);
WebSettings appwebsettings = webView.getSettings();
appwebsettings.setLoadsImagesAutomatically(true);
appwebsettings.setJavaScriptEnabled(true);
appwebsettings.setAllowContentAccess(true);
appwebsettings.setAllowFileAccess(true);
url = getIntent().getStringExtra("URL_NAME");
webView.loadUrl(url);
webView.requestFocus();
webView.setWebViewClient(new WebViewClient(){
@Override
public void onPageFinished(WebView view, String url) {
swipeRefreshLayout.setEnabled(false);
super.onPageFinished(view, url);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webView.setWebChromeClient(new WebChromeClient(){
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
}
@Override
public void onReceivedIcon(WebView view, Bitmap icon) {
super.onReceivedIcon(view, icon);
}
});
if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.M){
if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)== PackageManager.PERMISSION_DENIED){
Log.d("permission", "permission denied to WRITE_EXTERNAL_STORAGE - requesting it");
String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions,1);
}
}
webView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition,
String mimeType, long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie",cookies);
request.addRequestHeader("User-Agent",userAgent);
request.setDescription("Downloading File");
request.setTitle(URLUtil.guessFileName(url,contentDisposition,mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
URLUtil.guessFileName(url, contentDisposition, mimeType));
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
downloadManager.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_SHORT).show();
}
});
@Override
protected void onStart() {
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(networkChangeListener, filter);
super.onStart();
}
@Override
protected void onStop() {
unregisterReceiver(networkChangeListener);
super.onStop();
}
@Override
public void onBackPressed() {
if(webView.canGoBack()){
webView.goBack();
}else {
finish();
super.onBackPressed();
}
}
@Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
}
}
这是我的 Webview 布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".WebViewActivity">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
提前致谢。
感谢@blackapps 的建议。
我发现我的愚蠢问题的答案很简单。
我坚持使用URLUtil.guessFileName(url,contentDisposition,mimeType))
因为当我下载pdf文件时,下载的文件名将与我客户网站上上传的文件名相同。
所以我刚才做的是添加这个等式 fileName = URLUtil.guessFileName(url,contentDisposition,mimeType))
并在下载管理器中注册接收器然后在 pdf 下载完成后创建反应。
public class WebViewActivity extends AppCompatActivity {
...
private String fileName;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
webView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition,
String mimeType, long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
//setup the fileName
fileName = URLUtil.guessFileName(url,contentDisposition,mimeType);
request.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie",cookies);
request.addRequestHeader("User-Agent",userAgent);
request.setDescription("Downloading File");
request.setTitle(fileName));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
fileName);
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
//Registering receiver in Download Manager
registerReceiver(onCompleted, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
downloadManager.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_SHORT).show();
}
});
...
BroadcastReceiver onCompleted = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context.getApplicationContext(), "Download Finish", Toast.LENGTH_SHORT).show();
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + fileName);
Uri uri = FileProvider.getUriForFile(WebViewActivity.this, "com.example.app"+".provider",file);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(uri, "application/pdf");
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(i);
}
};
}
我有一个 webview 应用程序,它具有 pdf 下载功能,可以从一些不同的网站下载 pdf 文件。我想知道如何在下载后立即打开pdf。我的应用程序中还没有 pdf reader,因为我不知道如何应用它。
我已经阅读了我提出的类似问题的所有答案,但所有答案都不适用。问题是 pdf 的名称是基于上传者设置的,所以 pdf 文件的名称会因访问的网站而异。
下面的代码中,下载的pdf文件生成的名称是根据站点上的pdf名称生成的,不是我定的。
是否可以根据代码打开pdf文件,还是我应该修改代码?
package com.example.app;
public class WebViewActivity extends AppCompatActivity {
String url = "";
NetworkChangeListener networkChangeListener = new NetworkChangeListener();
private boolean multiple_files = true;
private static String file_type = "*/*";
private ValueCallback<Uri> file_data;
private ValueCallback<Uri[]> file_path;
private final static int file_req_code = 1;
private static final String TAG = WebViewActivity.class.getSimpleName();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = findViewById(R.id.webView);
WebSettings appwebsettings = webView.getSettings();
appwebsettings.setLoadsImagesAutomatically(true);
appwebsettings.setJavaScriptEnabled(true);
appwebsettings.setAllowContentAccess(true);
appwebsettings.setAllowFileAccess(true);
url = getIntent().getStringExtra("URL_NAME");
webView.loadUrl(url);
webView.requestFocus();
webView.setWebViewClient(new WebViewClient(){
@Override
public void onPageFinished(WebView view, String url) {
swipeRefreshLayout.setEnabled(false);
super.onPageFinished(view, url);
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webView.setWebChromeClient(new WebChromeClient(){
@Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
}
@Override
public void onReceivedIcon(WebView view, Bitmap icon) {
super.onReceivedIcon(view, icon);
}
});
if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.M){
if(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)== PackageManager.PERMISSION_DENIED){
Log.d("permission", "permission denied to WRITE_EXTERNAL_STORAGE - requesting it");
String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
requestPermissions(permissions,1);
}
}
webView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition,
String mimeType, long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie",cookies);
request.addRequestHeader("User-Agent",userAgent);
request.setDescription("Downloading File");
request.setTitle(URLUtil.guessFileName(url,contentDisposition,mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
URLUtil.guessFileName(url, contentDisposition, mimeType));
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
downloadManager.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_SHORT).show();
}
});
@Override
protected void onStart() {
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(networkChangeListener, filter);
super.onStart();
}
@Override
protected void onStop() {
unregisterReceiver(networkChangeListener);
super.onStop();
}
@Override
public void onBackPressed() {
if(webView.canGoBack()){
webView.goBack();
}else {
finish();
super.onBackPressed();
}
}
@Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
}
}
这是我的 Webview 布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".WebViewActivity">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
提前致谢。
感谢@blackapps 的建议。
我发现我的愚蠢问题的答案很简单。
我坚持使用URLUtil.guessFileName(url,contentDisposition,mimeType))
因为当我下载pdf文件时,下载的文件名将与我客户网站上上传的文件名相同。
所以我刚才做的是添加这个等式 fileName = URLUtil.guessFileName(url,contentDisposition,mimeType))
并在下载管理器中注册接收器然后在 pdf 下载完成后创建反应。
public class WebViewActivity extends AppCompatActivity {
...
private String fileName;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
webView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition,
String mimeType, long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
//setup the fileName
fileName = URLUtil.guessFileName(url,contentDisposition,mimeType);
request.setMimeType(mimeType);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie",cookies);
request.addRequestHeader("User-Agent",userAgent);
request.setDescription("Downloading File");
request.setTitle(fileName));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
fileName);
DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
//Registering receiver in Download Manager
registerReceiver(onCompleted, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
downloadManager.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_SHORT).show();
}
});
...
BroadcastReceiver onCompleted = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context.getApplicationContext(), "Download Finish", Toast.LENGTH_SHORT).show();
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + fileName);
Uri uri = FileProvider.getUriForFile(WebViewActivity.this, "com.example.app"+".provider",file);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(uri, "application/pdf");
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(i);
}
};
}