Search in sources :

Example 96 with WebViewClient

use of android.webkit.WebViewClient in project baker-android by bakerframework.

the class MagazineActivity method setPagerView.

@SuppressLint("SetJavaScriptEnabled")
private void setPagerView(final BookJson book) {
    String path = "file://".concat(Configuration.getMagazinesDirectory(this)).concat(File.separator).concat(book.getMagazineName());
    if (STANDALONE_MODE) {
        boolean fromAssets = !this.getResources().getBoolean(R.bool.sa_read_from_custom_directory);
        if (fromAssets) {
            path = "file:///android_asset".concat(File.separator).concat(getString(R.string.sa_books_directory)).concat(File.separator).concat(book.getMagazineName());
        }
    } else if (ENABLE_TUTORIAL) {
        path = "file:///android_asset".concat(File.separator).concat("abaker_usage");
    }
    if (book.getLiveUrl() != null) {
        path = book.getLiveUrl();
    }
    final String finalPath = path;
    Log.d(this.getClass().toString(), "THE PATH FOR LOADING THE PAGES WILL BE: " + finalPath);
    // ViewPager and its adapters use support library
    // fragments, so use getSupportFragmentManager.
    webViewPagerAdapter = new WebViewFragmentPagerAdapter(getSupportFragmentManager(), book, finalPath, this);
    pager = (CustomWebViewPager) findViewById(R.id.pager);
    pager.setAdapter(webViewPagerAdapter);
    // Bind the title indicator to the adapter
    LinePageIndicator indicator = (LinePageIndicator) findViewById(R.id.indicator);
    if (!ENABLE_TUTORIAL) {
        indicator.setVisibility(View.GONE);
    }
    indicator.setViewPager(pager);
    indicator.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            super.onPageSelected(position);
            if (hasElapsedTime) {
                Long timeElapsed = System.currentTimeMillis() - startedTime;
                if (timeElapsed > resources.getInteger(R.integer.ga_page_view_time_elapsed))
                    ((ABakerApp) MagazineActivity.this.getApplication()).sendTimingEvent(metaBakerPageCategory, timeElapsed, getString(R.string.issue_page_view), metaBakerPageName);
                ((ABakerApp) MagazineActivity.this.getApplication()).sendEvent(metaBakerPageCategory, getString(R.string.issue_page_view), metaBakerPageName);
                startedTime = 0L;
                hasElapsedTime = false;
                previousIndex = -1;
                metaBakerPageName = "";
                metaBakerPageCategory = "";
            }
            Log.d(this.getClass().getName(), "Loading page at index: " + position);
            detectFirstOrLastPage();
            if (resources.getBoolean(R.bool.ga_enable) && resources.getBoolean(R.bool.ga_register_page_view_event)) {
                String page = finalPath + book.getMagazineName() + File.separator + book.getContents().get(position);
                Map<String, String> tags = getBakerMetaTags(page);
                if (tags.containsKey("baker-page-name")) {
                    String name = tags.get("baker-page-name");
                    String category = tags.containsKey("baker-page-category") ? tags.get("baker-page-category") : getString(R.string.issues_category);
                    name = (name.isEmpty()) ? book.getContents().get(position) : name;
                    category = (category.isEmpty()) ? getString(R.string.issues_category) : category;
                    if (resources.getBoolean(R.bool.ga_register_page_view_time_elapsed_event)) {
                        startedTime = System.currentTimeMillis();
                        hasElapsedTime = true;
                        previousIndex = position;
                        metaBakerPageName = name;
                        metaBakerPageCategory = category;
                    } else {
                        ((ABakerApp) MagazineActivity.this.getApplication()).sendEvent(category, getString(R.string.issue_page_view), name);
                    }
                }
            }
        }
    });
    CustomWebView viewIndex = (CustomWebView) findViewById(R.id.webViewIndex);
    viewIndex.getSettings().setJavaScriptEnabled(true);
    viewIndex.getSettings().setUseWideViewPort(true);
    viewIndex.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String stringUrl) {
            // mailto links will be handled by the OS.
            if (stringUrl.startsWith("mailto:")) {
                Uri uri = Uri.parse(stringUrl);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            } else {
                try {
                    URL url = new URL(stringUrl);
                    // We try to remove the referrer string to avoid passing it to the server in case the URL is an external link.
                    String referrer = "";
                    if (url.getQuery() != null) {
                        Map<String, String> variables = Configuration.splitUrlQueryString(url);
                        String finalQueryString = "";
                        for (Map.Entry<String, String> entry : variables.entrySet()) {
                            if (entry.getKey().equals("referrer")) {
                                referrer = entry.getValue();
                            } else {
                                finalQueryString += entry.getKey() + "=" + entry.getValue() + "&";
                            }
                        }
                        if (!finalQueryString.isEmpty()) {
                            finalQueryString = "?" + finalQueryString.substring(0, finalQueryString.length() - 1);
                        }
                        stringUrl = stringUrl.replace("?" + url.getQuery(), finalQueryString);
                    }
                    if (!url.getProtocol().equals("file")) {
                        Log.d("REFERRER>>>", "THE REFERRER IS: " + referrer);
                        if (referrer.equals(MagazineActivity.this.getString(R.string.url_external_referrer))) {
                            Uri uri = Uri.parse(stringUrl);
                            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                            startActivity(intent);
                        } else if (referrer.equals(MagazineActivity.this.getString(R.string.url_gindpubs_referrer))) {
                            MagazineActivity.this.openLinkInModal(stringUrl);
                            return true;
                        } else {
                            // We return false to tell the webview that we are not going to handle the URL override.
                            return false;
                        }
                    } else {
                        stringUrl = url.getPath().substring(url.getPath().lastIndexOf("/") + 1);
                        Log.d(">>>URL_DATA", "FINAL INTERNAL HTML FILENAME = " + stringUrl);
                        int index = MagazineActivity.this.getJsonBook().getContents().indexOf(stringUrl);
                        if (index != -1) {
                            Log.d(this.getClass().toString(), "Index to load: " + index + ", page: " + stringUrl);
                            MagazineActivity.this.getPager().setCurrentItem(index);
                            view.setVisibility(View.GONE);
                        } else {
                            // If the file DOES NOT exist, we won't load it.
                            File htmlFile = new File(url.getPath());
                            if (htmlFile.exists()) {
                                return false;
                            }
                        }
                    }
                } catch (MalformedURLException ex) {
                    Log.d(">>>URL_DATA", ex.getMessage());
                } catch (UnsupportedEncodingException ex) {
                }
            }
            return true;
        }
    });
    viewIndex.loadUrl(path + File.separator + "index.html");
    viewIndex.setBackgroundColor(0x00000000);
    viewIndex.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
}
Also used : MalformedURLException(java.net.MalformedURLException) LinePageIndicator(com.viewpagerindicator.LinePageIndicator) WebViewFragmentPagerAdapter(com.baker.abaker.views.WebViewFragmentPagerAdapter) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Intent(android.content.Intent) ViewPager(android.support.v4.view.ViewPager) CustomWebViewPager(com.baker.abaker.views.CustomWebViewPager) Uri(android.net.Uri) SuppressLint(android.annotation.SuppressLint) URL(java.net.URL) CustomWebView(com.baker.abaker.views.CustomWebView) CustomWebView(com.baker.abaker.views.CustomWebView) WebView(android.webkit.WebView) HashMap(java.util.HashMap) Map(java.util.Map) File(java.io.File) WebViewClient(android.webkit.WebViewClient) SuppressLint(android.annotation.SuppressLint)

Example 97 with WebViewClient

use of android.webkit.WebViewClient in project baker-android by bakerframework.

the class GindActivity method loadingScreen.

private void loadingScreen() {
    Log.d(this.getClass().getName(), "Showing loading screen.");
    setContentView(R.layout.loading);
    WebView webview = (WebView) findViewById(R.id.loadingWebView);
    webview.getSettings().setJavaScriptEnabled(true);
    webview.getSettings().setUseWideViewPort(true);
    webview.getSettings().setLoadWithOverviewMode(true);
    webview.setBackgroundColor(Color.TRANSPARENT);
    webview.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    });
    webview.loadUrl(getString(R.string.loadingUrl));
}
Also used : WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient)

Example 98 with WebViewClient

use of android.webkit.WebViewClient in project baker-android by bakerframework.

the class ModalActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_modal);
    // Here we allow the user to rotate the screen.
    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
    Intent intent = getIntent();
    String url = intent.getStringExtra(MagazineActivity.MODAL_URL);
    orientation = intent.getIntExtra(MagazineActivity.ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_SENSOR);
    // Click on the CLOSE button.
    findViewById(R.id.btnCloseModal).setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            ModalActivity.this.finish();
        }
    });
    WebView webView = (WebView) this.findViewById(R.id.modalWebView);
    webView.getSettings().setJavaScriptEnabled(true);
    // Set zoom enabled/disabled
    webView.getSettings().setSupportZoom(true);
    // Support zoom like normal browsers
    webView.getSettings().setUseWideViewPort(true);
    // Disable zoom buttons
    webView.getSettings().setDisplayZoomControls(false);
    // Add zoom controls
    webView.getSettings().setBuiltInZoomControls(true);
    // Load the page on the maximum zoom out available.
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    });
    webView.loadUrl(url);
}
Also used : Intent(android.content.Intent) WebView(android.webkit.WebView) View(android.view.View) WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient)

Example 99 with WebViewClient

use of android.webkit.WebViewClient in project baker-android by bakerframework.

the class WebViewFragment method onCreateView.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    this.activity = (MagazineActivity) this.getActivity();
    // The last two arguments ensure LayoutParams are inflated
    // properly.
    View rootView = inflater.inflate(R.layout.fragment_collection_object, container, false);
    Bundle args = getArguments();
    customViewContainer = (FrameLayout) this.getActivity().findViewById(R.id.customViewContainer);
    webView = (CustomWebView) rootView.findViewById(R.id.webpage1);
    progressBarContainer = (FrameLayout) rootView.findViewById(R.id.progressBarContainer);
    // Enable javascript
    webView.getSettings().setJavaScriptEnabled(true);
    // Set zoom enabled/disabled
    webView.getSettings().setSupportZoom(true);
    // Support zoom like normal browsers
    webView.getSettings().setUseWideViewPort(true);
    // Disable zoom buttons
    webView.getSettings().setDisplayZoomControls(false);
    // Add zoom controls
    webView.getSettings().setBuiltInZoomControls(true);
    // Load the page on the maximum zoom out available.
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.setWebChromeClient(chromeClient);
    webView.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String stringUrl) {
            // mailto links will be handled by the OS.
            if (stringUrl.startsWith("mailto:")) {
                Uri uri = Uri.parse(stringUrl);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            } else {
                try {
                    URL url = new URL(stringUrl);
                    // We try to remove the referrer string to avoid passing it to the server in case the URL is an external link.
                    String referrer = "";
                    if (url.getQuery() != null) {
                        Map<String, String> variables = Configuration.splitUrlQueryString(url);
                        String finalQueryString = "";
                        for (Map.Entry<String, String> entry : variables.entrySet()) {
                            if (entry.getKey().equals("referrer")) {
                                referrer = entry.getValue();
                            } else {
                                finalQueryString += entry.getKey() + "=" + entry.getValue() + "&";
                            }
                        }
                        if (!finalQueryString.isEmpty()) {
                            finalQueryString = "?" + finalQueryString.substring(0, finalQueryString.length() - 1);
                        }
                        stringUrl = stringUrl.replace("?" + url.getQuery(), finalQueryString);
                    }
                    if (!url.getProtocol().equals("file")) {
                        Log.d("REFERRER>>>", "THE REFERRER IS: " + referrer);
                        if (referrer.equals(WebViewFragment.this.activity.getString(R.string.url_external_referrer))) {
                            Uri uri = Uri.parse(stringUrl);
                            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                            startActivity(intent);
                        } else if (referrer.equals(WebViewFragment.this.activity.getString(R.string.url_gindpubs_referrer))) {
                            WebViewFragment.this.activity.openLinkInModal(stringUrl);
                            return true;
                        } else {
                            // We return false to tell the webview that we are not going to handle the URL override.
                            return false;
                        }
                    } else {
                        stringUrl = url.getPath().substring(url.getPath().lastIndexOf("/") + 1);
                        Log.d(">>>URL_DATA", "FINAL INTERNAL HTML FILENAME = " + stringUrl);
                        int index = activity.getJsonBook().getContents().indexOf(stringUrl);
                        if (index != -1) {
                            Log.d(this.getClass().toString(), "Index to load: " + index + ", page: " + stringUrl);
                            activity.getPager().setCurrentItem(index);
                            view.setVisibility(View.GONE);
                        } else {
                            // If the file DOES NOT exist, we won't load it.
                            File htmlFile = new File(url.getPath());
                            if (htmlFile.exists()) {
                                return false;
                            }
                        }
                    }
                } catch (MalformedURLException ex) {
                    Log.d(">>>URL_DATA", ex.getMessage());
                } catch (UnsupportedEncodingException ex) {
                }
            }
            return true;
        }
    });
    webView.loadUrl(args.getString(ARG_OBJECT));
    return rootView;
}
Also used : MalformedURLException(java.net.MalformedURLException) Bundle(android.os.Bundle) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Intent(android.content.Intent) View(android.view.View) WebView(android.webkit.WebView) Uri(android.net.Uri) URL(java.net.URL) WebView(android.webkit.WebView) Map(java.util.Map) File(java.io.File) WebViewClient(android.webkit.WebViewClient)

Example 100 with WebViewClient

use of android.webkit.WebViewClient in project JustAndroid by chinaltz.

the class WebViewActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_webview);
    ButterKnife.bind(this);
    Intent in = getIntent();
    String title = in.getStringExtra("title");
    String url = in.getStringExtra("url");
    if (AbStrUtil.isEmpty(title)) {
        navTitle.setText("网页");
    } else {
        navTitle.setText(title);
    }
    navBack.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            finish();
        }
    });
    // 设置js可以直接打开窗口,如window.open(),默认为false
    webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    // 是否允许执行js,默认为false。设置true时,会提醒可能造成XSS漏洞
    webview.getSettings().setJavaScriptEnabled(true);
    // 是否可以缩放,默认true
    webview.getSettings().setSupportZoom(true);
    // 是否显示缩放按钮,默认false
    webview.getSettings().setBuiltInZoomControls(true);
    // 设置此属性,可任意比例缩放。大视图模式
    webview.getSettings().setUseWideViewPort(true);
    // 和setUseWideViewPort(true)一起解决网页自适应问题
    webview.getSettings().setLoadWithOverviewMode(true);
    // 是否使用缓存
    webview.getSettings().setAppCacheEnabled(true);
    // DOM Storage
    webview.getSettings().setDomStorageEnabled(true);
    webview.getSettings().setUserAgentString("User-Agent:Android");
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        webview.getSettings().setMixedContentMode(webview.getSettings().MIXED_CONTENT_ALWAYS_ALLOW);
    }
    // 设置用户代理,一般不用
    webview.loadUrl(url);
    // 设置WebViewClient
    webview.setWebViewClient(new WebViewClient() {

        // url拦截
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // Toast.makeText(ActivityMain.this, " 拦截到url:" + url,Toast.LENGTH_SHORT).show();
            // 使用自己的WebView组件来响应Url加载事件,而不是使用默认浏览器器加载页面
            view.loadUrl(url);
            // 相应完成返回true
            return true;
        // return super.shouldOverrideUrlLoading(view, url);
        }

        // 页面开始加载
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // Toast.makeText(ActivityMain.this, "onPageStarted:" + url,Toast.LENGTH_SHORT).show();
            super.onPageStarted(view, url, favicon);
        }

        // 页面加载完成
        @Override
        public void onPageFinished(WebView view, String url) {
            // Toast.makeText(ActivityMain.this, " onPageFinished:" + url,Toast.LENGTH_SHORT).show();
            super.onPageFinished(view, url);
        }

        // WebView加载的所有资源url
        @Override
        public void onLoadResource(WebView view, String url) {
            // Toast.makeText(ActivityMain.this, " onLoadResource:" + url,Toast.LENGTH_SHORT).show();
            super.onLoadResource(view, url);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            // Toast.makeText(ActivityMain.this,"错误url:" + failingUrl + "," + description,Toast.LENGTH_SHORT).show();
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
    });
}
Also used : Bitmap(android.graphics.Bitmap) Intent(android.content.Intent) WebView(android.webkit.WebView) ImageView(android.widget.ImageView) BindView(butterknife.BindView) TextView(android.widget.TextView) View(android.view.View) WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient)

Aggregations

WebViewClient (android.webkit.WebViewClient)247 WebView (android.webkit.WebView)229 WebSettings (android.webkit.WebSettings)77 View (android.view.View)71 WebChromeClient (android.webkit.WebChromeClient)69 SuppressLint (android.annotation.SuppressLint)61 Intent (android.content.Intent)60 Bitmap (android.graphics.Bitmap)59 WebResourceRequest (android.webkit.WebResourceRequest)35 TextView (android.widget.TextView)26 LinearLayout (android.widget.LinearLayout)22 WebResourceError (android.webkit.WebResourceError)21 WebResourceResponse (android.webkit.WebResourceResponse)16 Uri (android.net.Uri)15 SslError (android.net.http.SslError)13 Bundle (android.os.Bundle)13 Toolbar (android.support.v7.widget.Toolbar)13 KeyEvent (android.view.KeyEvent)13 SslErrorHandler (android.webkit.SslErrorHandler)13 TargetApi (android.annotation.TargetApi)12