简体   繁体   English

安卓问题用mailto和tel打开下载和网址

[英]Android problems opening downloads and urls with mailto and tel

So I am stuck on a issue with my webapp that runs inside a webview from android studio. 所以我遇到了一个问题,我的webapp在android studio的webview中运行。

I want download like pdf file to be downloaded and opend in the native app on the phone. 我希望下载像pdf文件下载并在手机上的本机应用程序中打开。 This work fine by using the download manager from android studio. 通过使用android studio的下载管理器,这工作正常。 How ever I also have links that start with "mailto:" and "tel:" those links give me an error when I don't override the method "shouldOverrideUrlLoading" where I can check what kind of url it is. 我怎么也有以“mailto:”和“tel:”开头的链接,当我不覆盖方法“shouldOverrideUrlLoading”时,这些链接会给我一个错误,我可以检查它是什么类型的URL。 And then open the propper inten. 然后打开propper的意图。

So when I combine the 2 the downloadmanager and the custom NavigationHandler that extends the WebViewClient, it doesn't work as expected. 因此,当我将下载管理器和扩展WebViewClient的自定义NavigationHandler结合使用时,它无法按预期工作。

For a better understanding of what is happening. 为了更好地了解正在发生的事情。

  1. When I hit a button with a pdf file it downloads the file gives a toast message and opens the file with the native app on the phone. 当我点击一个带有pdf文件的按钮时,它会下载该文件,提供一个Toast消息,然后在手机上使用本机应用程序打开该文件。 This is without overriding the "shouldOverrideURLLoading" and without my class that extends the WebViewClient. 这不会覆盖“shouldOverrideURLLoading”,也不会覆盖扩展WebViewClient的类。

  2. When I also use my own NavigationHandler witch extends from WebViewClient, my urls with "mailto:" and "tel:" open with native apps on the phone. 当我还使用我自己的NavigationHandler女巫从WebViewClient扩展时,我的网址“mailto:”和“tel:”在手机上打开本机应用程序。 When I now hit a button with a pdf file it is opend in a browser to be downloaded. 当我现在点击带有pdf文件的按钮时,它将在浏览器中打开以进行下载。 Witch I don't want. 女巫我不想要。 I have tried numerous things to solf the problem but until now without succes. 我已经尝试了很多东西来解决这个问题,但直到现在还没有成功。

I run a website app inside of a WebViewClient. 我在WebViewClient中运行一个网站应用程序。

PS sorry for the shitty code but it's new to me and haven't find my way jet in coding in Android Studio. PS对不起这些糟糕的代码感到遗憾,但这对我来说并不新鲜,并且在Android Studio中没有找到我的编码方式。

My NavigationHandler class 我的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;
    }
}

My MainActivity Class 我的MainActivity类

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);
    }

}

This code downloads any file. 此代码下载任何文件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Android WebViewClient中打开tel:和mailto:链接 - Opening tel: & mailto: links in Android WebViewClient mailto:和tel:在android webbrowser中 - mailto: and tel: in android webbrowser Android WebView:电话:地理位置:Mailto:正确处理 - Android WebView: Tel: Geo: Mailto: Proper Handling Android上mailto和tel链接的页面重定向 - Page redirection for mailto and tel links on Android 如何在 android webview 中处理 mailto 和 tel - How can I handle mailto and tel in android webview 升级到cordova 3.6.3后,“tel”、“sms”和“mailto”在Android中不再有效 - “tel”, “sms”, and “mailto” no longer working in Android after upgrading to cordova 3.6.3 Android WebView“tel:”和“mailto:”链接显示未找到网页 - Android WebView “tel:” & “mailto:”links show web page not found 在tel 4中使用扩展的问题:Android 4上的超链接 - Problems using extensions in tel: hyperlinks on Android 4 如何在 Android TextView 中使所有类型的 HTML 链接都可点击? (工作解决方案!使用 mailto: 和 tel:) - How to make all types of HTML links clickable in Android TextView? (Working Solution! With mailto: and tel:) tel和mailto Links停止在cordova应用程序中工作 - tel and mailto Links Stopped Working in cordova app
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM