所以我遇到了一个问题,我的webapp在android studio的webview中运行。
我想要下载pdf文件下载并在手机上的原生应用中打开。通过使用android studio的下载管理器,这工作正常。 我怎么也有以“mailto:”和“tel:”开头的链接,当我不覆盖方法“shouldOverrideUrlLoading”时,这些链接会给我一个错误,我可以检查它是什么类型的URL。然后打开propper inten。
因此,当我将下载管理器和扩展WebViewClient的自定义NavigationHandler结合使用时,它无法按预期工作。
为了更好地了解正在发生的事情。
当我点击带有pdf文件的按钮时,它会下载该文件,提供一个Toast消息并在手机上使用本机应用程序打开该文件。这不会覆盖“shouldOverrideURLLoading”,也不会覆盖扩展WebViewClient的类。
当我还使用自己的NavigationHandler时,从WebViewClient扩展, 我的网址用“mailto:”和“tel:”打开手机上的原生应用程序。 当我现在点击带有pdf文件的按钮时,它将在浏览器中打开以进行下载。女巫我不想要。我已经尝试了很多东西来解决这个问题,但直到现在还没有成功。
我在WebViewClient中运行一个网站应用程序。
P.S。对于糟糕的代码感到抱歉,但这对我来说是新手,并且在Android Studio中没有找到我的编码方式。
我的NavigationHandler类
package nl.firejob.selector;
import android.content.Intent;
import android.net.Uri;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class NavigationHandler extends WebViewClient {
private static final String TEL_PREFIX = "tel:";
private static final String MAILTO_PREFIX = "mailto:";
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if ( url.startsWith( TEL_PREFIX ) ) {
// This is a tel link, which should be opened with the native thing.
Intent tel = new Intent( Intent.ACTION_DIAL, Uri.parse( url ) );
view.getContext().startActivity( tel );
return true;
} else if ( url.startsWith( MAILTO_PREFIX ) ) {
// This is a mail link, which should be opened with the other native thing.
Intent mail = new Intent(Intent.ACTION_SENDTO);
mail.setType("message/rfc822");
mail.setData(Uri.parse( url ));
view.getContext().startActivity( mail );
return true;
} else if ( Uri.parse(url).getHost().startsWith("myurl.com") ) {
// This is what we want to show in the app, so let the WebView handle it.
return false;
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse( url ) );
view.getContext().startActivity( intent );
return true;
}
}
我的主要活动类
package nl.firejob.selector;
import android.Manifest;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;
import java.io.File;
public class MainActivity extends AppCompatActivity {
private WebView mWebView;
private DownloadManager dm;
private Long myDownloadReference;
private BroadcastReceiver receiveDownloadComplete;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webView);
// Allow webview to use javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
// Stop local links/redirects from opening in browser instead of WebView
mWebView.setWebViewClient(new NavigationHandler() {
@Override
public void onPageFinished(WebView view, String url) {
// Show the webview
findViewById(R.id.webView).setVisibility(View.VISIBLE);
// Hide splashscreen objects
findViewById(R.id.imageLogo).setVisibility(View.GONE);
findViewById(R.id.textLogo).setVisibility(View.GONE);
}
});
mWebView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
if( haveStoragePermission()) {
Log.i("download url",url);
//for downloading directly through download manager
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.allowScanningByMediaScanner();
request.setVisibleInDownloadsUi(true);
request.setDescription("Doorvoerboek").setTitle("doorvoerboek.pdf");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "doorvoerboek.pdf");
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
myDownloadReference = dm.enqueue(request);
IntentFilter intentFilter = new IntentFilter( dm.ACTION_DOWNLOAD_COMPLETE);
receiveDownloadComplete = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (myDownloadReference == reference) {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(reference);
Cursor cursor = dm.query(query);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
int status = cursor.getInt(columnIndex);
int fileNameIndex = cursor.getColumnIndex(DownloadManager.COLUMN_TITLE);
String saveFilePath = cursor.getString(fileNameIndex);
Log.i("filename",saveFilePath);
int columnReason = cursor.getColumnIndex(DownloadManager.COLUMN_REASON);
int reason = cursor.getInt(columnReason);
switch (status){
case DownloadManager.STATUS_SUCCESSFUL:
Toast.makeText(MainActivity.this, "Download Complete", Toast.LENGTH_LONG).show();
Log.i("dir", Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() );
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() +"/doorvoerboek.pdf");
Intent intentView = new Intent(Intent.ACTION_VIEW);
intentView.setDataAndType(Uri.fromFile(file),"application/pdf");
intentView.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intentView);
break;
}
}
}
};
registerReceiver(receiveDownloadComplete,intentFilter);
}
}
});
mWebView.loadUrl("http://myurl.com/");
}
public boolean haveStoragePermission() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.e("Permission error","You have permission");
return true;
} else {
Log.e("Permission error","You have asked for permission");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //you dont need to worry about these stuff below api level 23
Log.e("Permission error","You already have the permission");
return true;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
//if Back key pressed and webview can navigate to previous page
mWebView.goBack();
// go back to previous page
return true;
}
else
{
finish();
// finish the activity
}
return super.onKeyDown(keyCode, event);
}
}
答案 0 :(得分:0)
此代码下载任何文件。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView) findViewById(R.id.webView);
spinner = (ProgressBar) findViewById(R.id.progressBar1);
webview.setWebViewClient(new CustomWebViewClient());
webview.getSettings().setUseWideViewPort(true);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setBuiltInZoomControls(true);
webview.getSettings().setDisplayZoomControls(false);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
webview.loadUrl("http://www.website.com");
//Download file code stackoverflow.com
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.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getApplicationContext(), "downloading",
Toast.LENGTH_LONG).show();
}
});
// Download section of code
} // Close of onCreate
// mailto code stackoverflow.com
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if( url.startsWith("http:") || url.startsWith("https:") ) {
return false;
}
// Otherwise allow the OS to handle it
else if (url.startsWith("tel:")) {
Intent tel = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(tel);
return true;
}
else if (url.startsWith("mailto:")) {
String body = "Enter your Question, Enquiry or Feedback below:\n\n";
Intent mail = new Intent(Intent.ACTION_SEND);
Intent intent = mail.setType("application/octet-stream");
MailTo recipient = MailTo.parse(url);
mail.putExtra(Intent.EXTRA_EMAIL, new String[]{recipient.getTo()});
mail.putExtra(Intent.EXTRA_SUBJECT, "Contact");
mail.putExtra(Intent.EXTRA_TEXT, body);
startActivity(mail);
return true;
}
return true;
}
}
// mailto section of code