簡體   English   中英

安卓問題用mailto和tel打開下載和網址

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

所以我遇到了一個問題,我的webapp在android studio的webview中運行。

我希望下載像pdf文件下載並在手機上的本機應用程序中打開。 通過使用android studio的下載管理器,這工作正常。 我怎么也有以“mailto:”和“tel:”開頭的鏈接,當我不覆蓋方法“shouldOverrideUrlLoading”時,這些鏈接會給我一個錯誤,我可以檢查它是什么類型的URL。 然后打開propper的意圖。

因此,當我將下載管理器和擴展WebViewClient的自定義NavigationHandler結合使用時,它無法按預期工作。

為了更好地了解正在發生的事情。

  1. 當我點擊一個帶有pdf文件的按鈕時,它會下載該文件,提供一個Toast消息,然后在手機上使用本機應用程序打開該文件。 這不會覆蓋“shouldOverrideURLLoading”,也不會覆蓋擴展WebViewClient的類。

  2. 當我還使用我自己的NavigationHandler女巫從WebViewClient擴展時,我的網址“mailto:”和“tel:”在手機上打開本機應用程序。 當我現在點擊帶有pdf文件的按鈕時,它將在瀏覽器中打開以進行下載。 女巫我不想要。 我已經嘗試了很多東西來解決這個問題,但直到現在還沒有成功。

我在WebViewClient中運行一個網站應用程序。

PS對不起這些糟糕的代碼感到遺憾,但這對我來說並不新鮮,並且在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;
    }
}

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

}

此代碼下載任何文件。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM