android webview 跳轉

weixin_34292287發表於2018-01-02
package com.example.administrator.webtest;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;

import java.util.List;

public class MainActivity extends AppCompatActivity {
    EditText text;
    WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = findViewById(R.id.url);
        webView = findViewById(R.id.webview);
        initView();
        findViewById(R.id.go).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onGoClick();
            }
        });
    }

    private void initView() {
        webView.setWebChromeClient(new WebChromeClient());
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return openApp(url);
            }


            //開啟app
            private boolean openApp(String url) {
                if (TextUtils.isEmpty(url)) return false;
                try {
                    if (!url.startsWith("http") || !url.startsWith("https") || !url.startsWith("ftp")) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        List<ResolveInfo> list = getApplication().getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_ALL);
                        if (list.size() > 0) {
                            startActivity(intent);
                            return true;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
                return false;
            }
        });
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.setWebContentsDebuggingEnabled(true);
        }
    }

    private void onGoClick() {
        String url = text.getText().toString();
        webView.loadUrl(url);
    }
}

自帶瀏覽器 支援除錯

相關文章