Example usage for android.webkit URLUtil guessFileName

List of usage examples for android.webkit URLUtil guessFileName

Introduction

In this page you can find the example usage for android.webkit URLUtil guessFileName.

Prototype

public static final String guessFileName(String url, @Nullable String contentDisposition,
        @Nullable String mimeType) 

Source Link

Document

Guesses canonical filename that a download would have, using the URL and contentDisposition.

Usage

From source file:com.android.stockbrowser.DownloadHandler.java

private static void onDownloadNoStreamImpl(Activity activity, String url, String userAgent,
        String contentDisposition, String mimetype, String referer, boolean privateBrowsing) {

    String filename = URLUtil.guessFileName(url, contentDisposition, mimetype);

    // Check to see if we have an SDCard
    String status = Environment.getExternalStorageState();
    if (!status.equals(Environment.MEDIA_MOUNTED)) {
        int title;
        String msg;/*ww  w . j a  v a2  s  .  c  o m*/

        // Check to see if the SDCard is busy, same as the music app
        if (status.equals(Environment.MEDIA_SHARED)) {
            msg = activity.getString(R.string.download_sdcard_busy_dlg_msg);
            title = R.string.download_sdcard_busy_dlg_title;
        } else {
            msg = activity.getString(R.string.download_no_sdcard_dlg_msg, filename);
            title = R.string.download_no_sdcard_dlg_title;
        }

        new AlertDialog.Builder(activity).setTitle(title).setIconAttribute(android.R.attr.alertDialogIcon)
                .setMessage(msg).setPositiveButton(R.string.ok, null).show();
        return;
    }

    // java.net.URI is a lot stricter than KURL so we have to encode some
    // extra characters. Fix for b 2538060 and b 1634719
    WebAddress webAddress;
    try {
        webAddress = new WebAddress(url);
        webAddress.setPath(encodePath(webAddress.getPath()));
    } catch (Exception e) {
        // This only happens for very bad urls, we want to chatch the
        // exception here
        Log.e(LOGTAG, "Exception trying to parse url:" + url);
        return;
    }

    String addressString = webAddress.toString();
    Uri uri = Uri.parse(addressString);
    final DownloadManager.Request request;
    try {
        request = new DownloadManager.Request(uri);
    } catch (IllegalArgumentException e) {
        Toast.makeText(activity, R.string.cannot_download, Toast.LENGTH_SHORT).show();
        return;
    }
    request.setMimeType(mimetype);
    // set downloaded file destination to /sdcard/Download.
    // or, should it be set to one of several Environment.DIRECTORY* dirs depending on mimetype?
    try {
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
    } catch (IllegalStateException ex) {
        // This only happens when directory Downloads can't be created or it isn't a directory
        // this is most commonly due to temporary problems with sdcard so show appropriate string
        Log.w(LOGTAG, "Exception trying to create Download dir:", ex);
        Toast.makeText(activity, R.string.download_sdcard_busy_dlg_title, Toast.LENGTH_SHORT).show();
        return;
    }
    // let this downloaded file be scanned by MediaScanner - so that it can
    // show up in Gallery app, for example.
    request.allowScanningByMediaScanner();
    request.setDescription(webAddress.getHost());
    // XXX: Have to use the old url since the cookies were stored using the
    // old percent-encoded url.
    String cookies = "";//CookieManager.getInstance().getCookie(url, privateBrowsing);
    request.addRequestHeader("cookie", cookies);
    request.addRequestHeader("User-Agent", userAgent);
    if (!TextUtils.isEmpty(referer)) {
        request.addRequestHeader("Referer", referer);
    }
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    if (mimetype == null) {
        if (TextUtils.isEmpty(addressString)) {
            return;
        }
        // We must have long pressed on a link or image to download it. We
        // are not sure of the mimetype in this case, so do a head request
        new FetchUrlMimeType(activity, request, addressString, cookies, userAgent).start();
    } else {
        final DownloadManager manager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
        new Thread("StockBrowser download") {
            public void run() {
                manager.enqueue(request);
            }
        }.start();
    }
    Toast.makeText(activity, R.string.download_pending, Toast.LENGTH_SHORT).show();
}

From source file:com.android.browser.DownloadHandler.java

private static void onDownloadNoStreamImpl(Activity activity, String url, String userAgent,
        String contentDisposition, String mimetype, String referer, boolean privateBrowsing) {

    String filename = URLUtil.guessFileName(url, contentDisposition, mimetype);

    // Check to see if we have an SDCard
    String status = Environment.getExternalStorageState();
    if (!status.equals(Environment.MEDIA_MOUNTED)) {
        int title;
        String msg;//from w  w w . jav a 2  s .  co  m

        // Check to see if the SDCard is busy, same as the music app
        if (status.equals(Environment.MEDIA_SHARED)) {
            msg = activity.getString(R.string.download_sdcard_busy_dlg_msg);
            title = R.string.download_sdcard_busy_dlg_title;
        } else {
            msg = activity.getString(R.string.download_no_sdcard_dlg_msg, filename);
            title = R.string.download_no_sdcard_dlg_title;
        }

        new AlertDialog.Builder(activity).setTitle(title).setIconAttribute(android.R.attr.alertDialogIcon)
                .setMessage(msg).setPositiveButton(R.string.ok, null).show();
        return;
    }

    // java.net.URI is a lot stricter than KURL so we have to encode some
    // extra characters. Fix for b 2538060 and b 1634719
    WebAddress webAddress;
    try {
        webAddress = new WebAddress(url);
        webAddress.setPath(encodePath(webAddress.getPath()));
    } catch (Exception e) {
        // This only happens for very bad urls, we want to chatch the
        // exception here
        Log.e(LOGTAG, "Exception trying to parse url:" + url);
        return;
    }

    String addressString = webAddress.toString();
    Uri uri = Uri.parse(addressString);
    final DownloadManager.Request request;
    try {
        request = new DownloadManager.Request(uri);
    } catch (IllegalArgumentException e) {
        Toast.makeText(activity, R.string.cannot_download, Toast.LENGTH_SHORT).show();
        return;
    }
    request.setMimeType(mimetype);
    // set downloaded file destination to /sdcard/Download.
    // or, should it be set to one of several Environment.DIRECTORY* dirs depending on mimetype?
    try {
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
    } catch (IllegalStateException ex) {
        // This only happens when directory Downloads can't be created or it isn't a directory
        // this is most commonly due to temporary problems with sdcard so show appropriate string
        Log.w(LOGTAG, "Exception trying to create Download dir:", ex);
        Toast.makeText(activity, R.string.download_sdcard_busy_dlg_title, Toast.LENGTH_SHORT).show();
        return;
    }
    // let this downloaded file be scanned by MediaScanner - so that it can
    // show up in Gallery app, for example.
    request.allowScanningByMediaScanner();
    request.setDescription(webAddress.getHost());
    // XXX: Have to use the old url since the cookies were stored using the
    // old percent-encoded url.
    String cookies = CookieManager.getInstance().getCookie(url, privateBrowsing);
    request.addRequestHeader("cookie", cookies);
    request.addRequestHeader("User-Agent", userAgent);
    if (!TextUtils.isEmpty(referer)) {
        request.addRequestHeader("Referer", referer);
    }
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    if (mimetype == null) {
        if (TextUtils.isEmpty(addressString)) {
            return;
        }
        // We must have long pressed on a link or image to download it. We
        // are not sure of the mimetype in this case, so do a head request
        new FetchUrlMimeType(activity, request, addressString, cookies, userAgent).start();
    } else {
        final DownloadManager manager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
        new Thread("Browser download") {
            public void run() {
                manager.enqueue(request);
            }
        }.start();
    }
    Toast.makeText(activity, R.string.download_pending, Toast.LENGTH_SHORT).show();
}

From source file:com.sabaibrowser.DownloadHandler.java

private static void onDownloadNoStreamImpl(Activity activity, String url, String userAgent,
        String contentDisposition, String mimetype, String referer, boolean privateBrowsing) {

    String filename = URLUtil.guessFileName(url, contentDisposition, mimetype);

    // Check to see if we have an SDCard
    String status = Environment.getExternalStorageState();
    if (!status.equals(Environment.MEDIA_MOUNTED)) {
        int title;
        String msg;/* ww w  . j a v a 2s.c om*/

        // Check to see if the SDCard is busy, same as the music app
        if (status.equals(Environment.MEDIA_SHARED)) {
            msg = activity.getString(R.string.download_sdcard_busy_dlg_msg);
            title = R.string.download_sdcard_busy_dlg_title;
        } else {
            msg = activity.getString(R.string.download_no_sdcard_dlg_msg, filename);
            title = R.string.download_no_sdcard_dlg_title;
        }

        new AlertDialog.Builder(activity).setTitle(title).setIconAttribute(android.R.attr.alertDialogIcon)
                .setMessage(msg).setPositiveButton(R.string.ok, null).show();
        return;
    }

    // java.net.URI is a lot stricter than KURL so we have to encode some
    // extra characters. Fix for b 2538060 and b 1634719
    WebAddress webAddress;
    try {
        webAddress = new WebAddress(url);
        webAddress.setPath(encodePath(webAddress.getPath()));
    } catch (Exception e) {
        // This only happens for very bad urls, we want to chatch the
        // exception here
        Log.e(LOGTAG, "Exception trying to parse url:" + url);
        return;
    }

    String addressString = webAddress.toString();
    Uri uri = Uri.parse(addressString);
    final DownloadManager.Request request;
    try {
        request = new DownloadManager.Request(uri);
    } catch (IllegalArgumentException e) {
        Toast.makeText(activity, R.string.cannot_download, Toast.LENGTH_SHORT).show();
        return;
    }
    request.setMimeType(mimetype);
    // set downloaded file destination to /sdcard/Download.
    // or, should it be set to one of several Environment.DIRECTORY* dirs depending on mimetype?
    try {
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
    } catch (IllegalStateException ex) {
        // This only happens when directory Downloads can't be created or it isn't a directory
        // this is most commonly due to temporary problems with sdcard so show appropriate string
        Log.w(LOGTAG, "Exception trying to create Download dir:", ex);
        Toast.makeText(activity, R.string.download_sdcard_busy_dlg_title, Toast.LENGTH_SHORT).show();
        return;
    }
    // let this downloaded file be scanned by MediaScanner - so that it can
    // show up in Gallery app, for example.
    request.allowScanningByMediaScanner();
    request.setDescription(webAddress.getHost());
    // XXX: Have to use the old url since the cookies were stored using the
    // old percent-encoded url.
    String cookies = privateBrowsing ? "" : CookieManager.getInstance().getCookie(url);
    request.addRequestHeader("cookie", cookies);
    request.addRequestHeader("User-Agent", userAgent);
    if (!TextUtils.isEmpty(referer)) {
        request.addRequestHeader("Referer", referer);
    }
    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    if (mimetype == null) {
        if (TextUtils.isEmpty(addressString)) {
            return;
        }
        // We must have long pressed on a link or image to download it. We
        // are not sure of the mimetype in this case, so do a head request
        new FetchUrlMimeType(activity, request, addressString, cookies, userAgent).start();
    } else {
        final DownloadManager manager = (DownloadManager) activity.getSystemService(Context.DOWNLOAD_SERVICE);
        new Thread("Browser download") {
            public void run() {
                manager.enqueue(request);
            }
        }.start();
    }
    Toast.makeText(activity, R.string.download_pending, Toast.LENGTH_SHORT).show();
}

From source file:de.baumann.browser.Browser.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    WebView.enableSlowWholeDocumentDraw();
    setContentView(R.layout.activity_browser);
    helper_main.onStart(Browser.this);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);/*from w  w  w  . j  a va  2s  .com*/

    PreferenceManager.setDefaultValues(this, R.xml.user_settings, false);
    PreferenceManager.setDefaultValues(this, R.xml.user_settings_search, false);
    sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    sharedPref.edit().putInt("keyboard", 0).apply();
    sharedPref.getInt("keyboard", 0);

    customViewContainer = (FrameLayout) findViewById(R.id.customViewContainer);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    editText = (EditText) findViewById(R.id.editText);
    editText.setHint(R.string.app_search_hint);
    editText.clearFocus();

    imageButton = (ImageButton) findViewById(R.id.imageButton);
    imageButton.setVisibility(View.INVISIBLE);
    imageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mWebView.scrollTo(0, 0);
            imageButton.setVisibility(View.INVISIBLE);
            actionBar = getSupportActionBar();
            assert actionBar != null;
            if (!actionBar.isShowing()) {
                editText.setText(mWebView.getTitle());
                actionBar.show();
            }
            setNavArrows();
        }
    });

    SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe);
    assert swipeView != null;
    swipeView.setColorSchemeResources(R.color.colorPrimary, R.color.colorAccent);
    swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mWebView.reload();
        }
    });

    mWebView = (ObservableWebView) findViewById(R.id.webView);
    if (sharedPref.getString("fullscreen", "2").equals("2")
            || sharedPref.getString("fullscreen", "2").equals("3")) {
        mWebView.setScrollViewCallbacks(this);
    }

    mWebChromeClient = new myWebChromeClient();
    mWebView.setWebChromeClient(mWebChromeClient);

    imageButton_left = (ImageButton) findViewById(R.id.imageButton_left);
    imageButton_right = (ImageButton) findViewById(R.id.imageButton_right);

    if (sharedPref.getBoolean("arrow", false)) {
        imageButton_left.setVisibility(View.VISIBLE);
        imageButton_right.setVisibility(View.VISIBLE);
    } else {
        imageButton_left.setVisibility(View.INVISIBLE);
        imageButton_right.setVisibility(View.INVISIBLE);
    }

    helper_webView.webView_Settings(Browser.this, mWebView);
    helper_webView.webView_WebViewClient(Browser.this, swipeView, mWebView, editText);

    mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);

    if (isNetworkUnAvailable()) {
        if (sharedPref.getBoolean("offline", false)) {
            if (isNetworkUnAvailable()) { // loading offline
                mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
                Snackbar.make(mWebView, R.string.toast_cache, Snackbar.LENGTH_SHORT).show();
            }
        } else {
            Snackbar.make(mWebView, R.string.toast_noInternet, Snackbar.LENGTH_SHORT).show();
        }
    }

    mWebView.setDownloadListener(new DownloadListener() {

        public void onDownloadStart(final String url, String userAgent, final String contentDisposition,
                final String mimetype, long contentLength) {

            registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

            final String filename = URLUtil.guessFileName(url, contentDisposition, mimetype);
            Snackbar snackbar = Snackbar
                    .make(mWebView, getString(R.string.toast_download_1) + " " + filename, Snackbar.LENGTH_LONG)
                    .setAction(getString(R.string.toast_yes), new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                            request.addRequestHeader("Cookie", CookieManager.getInstance().getCookie(url));
                            request.allowScanningByMediaScanner();
                            request.setNotificationVisibility(
                                    DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
                            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                                    filename);
                            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                            dm.enqueue(request);

                            Snackbar.make(mWebView, getString(R.string.toast_download) + " " + filename,
                                    Snackbar.LENGTH_SHORT).show();
                        }
                    });
            snackbar.show();
        }
    });

    helper_editText.editText_Touch(editText, Browser.this, mWebView);
    helper_editText.editText_EditorAction(editText, Browser.this, mWebView);
    helper_editText.editText_FocusChange(editText, Browser.this);

    onNewIntent(getIntent());
    helper_main.grantPermissionsStorage(Browser.this);
}

From source file:de.baumann.browser.Browser_right.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    getWindow().setStatusBarColor(ContextCompat.getColor(Browser_right.this, R.color.colorTwoDark));

    WebView.enableSlowWholeDocumentDraw();
    setContentView(R.layout.activity_browser);
    helper_main.onStart(Browser_right.this);

    PreferenceManager.setDefaultValues(this, R.xml.user_settings, false);
    PreferenceManager.setDefaultValues(this, R.xml.user_settings_search, false);
    sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    sharedPref.edit()//from ww w. j  av a 2 s.  com
            .putString("openURL", sharedPref.getString("startURL", "https://github.com/scoute-dich/browser/"))
            .apply();
    sharedPref.edit().putInt("keyboard", 0).apply();
    sharedPref.getInt("keyboard", 0);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setBackgroundColor(ContextCompat.getColor(Browser_right.this, R.color.colorTwo));
    setSupportActionBar(toolbar);

    actionBar = getSupportActionBar();

    customViewContainer = (FrameLayout) findViewById(R.id.customViewContainer);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    editText = (EditText) findViewById(R.id.editText);
    editText.setVisibility(View.GONE);
    editText.setHint(R.string.app_search_hint);
    editText.clearFocus();

    urlBar = (TextView) findViewById(R.id.urlBar);

    imageButton = (ImageButton) findViewById(R.id.imageButton);
    imageButton.setVisibility(View.INVISIBLE);
    imageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mWebView.scrollTo(0, 0);
            imageButton.setVisibility(View.INVISIBLE);
            if (!actionBar.isShowing()) {
                urlBar.setText(mWebView.getTitle());
                actionBar.show();
            }
            helper_browser.setNavArrows(mWebView, imageButton_left, imageButton_right);
        }
    });

    SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe);
    assert swipeView != null;
    swipeView.setColorSchemeResources(R.color.colorTwo, R.color.colorAccent);
    swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mWebView.reload();
        }
    });

    mWebView = (ObservableWebView) findViewById(R.id.webView);
    if (sharedPref.getString("fullscreen", "2").equals("2")
            || sharedPref.getString("fullscreen", "2").equals("3")) {
        mWebView.setScrollViewCallbacks(this);
    }

    mWebChromeClient = new myWebChromeClient();
    mWebView.setWebChromeClient(mWebChromeClient);

    imageButton_left = (ImageButton) findViewById(R.id.imageButton_left);
    imageButton_right = (ImageButton) findViewById(R.id.imageButton_right);

    if (sharedPref.getBoolean("arrow", false)) {
        imageButton_left.setVisibility(View.VISIBLE);
        imageButton_right.setVisibility(View.VISIBLE);
    } else {
        imageButton_left.setVisibility(View.INVISIBLE);
        imageButton_right.setVisibility(View.INVISIBLE);
    }

    helper_webView.webView_Settings(Browser_right.this, mWebView);
    helper_webView.webView_WebViewClient(Browser_right.this, swipeView, mWebView, urlBar);

    mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);

    if (isNetworkUnAvailable()) {
        if (sharedPref.getBoolean("offline", false)) {
            if (isNetworkUnAvailable()) { // loading offline
                mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
                Snackbar.make(mWebView, R.string.toast_cache, Snackbar.LENGTH_SHORT).show();
            }
        } else {
            Snackbar.make(mWebView, R.string.toast_noInternet, Snackbar.LENGTH_SHORT).show();
        }
    }

    mWebView.setDownloadListener(new DownloadListener() {

        public void onDownloadStart(final String url, String userAgent, final String contentDisposition,
                final String mimetype, long contentLength) {

            registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

            final String filename = URLUtil.guessFileName(url, contentDisposition, mimetype);
            Snackbar snackbar = Snackbar
                    .make(mWebView, getString(R.string.toast_download_1) + " " + filename, Snackbar.LENGTH_LONG)
                    .setAction(getString(R.string.toast_yes), new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                            request.addRequestHeader("Cookie", CookieManager.getInstance().getCookie(url));
                            request.allowScanningByMediaScanner();
                            request.setNotificationVisibility(
                                    DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
                            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                                    filename);
                            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                            dm.enqueue(request);

                            Snackbar.make(mWebView, getString(R.string.toast_download) + " " + filename,
                                    Snackbar.LENGTH_SHORT).show();
                        }
                    });
            snackbar.show();
        }
    });

    helper_browser.toolbar(Browser_right.this, Browser_left.class, mWebView, toolbar);
    helper_editText.editText_EditorAction(editText, Browser_right.this, mWebView, urlBar);
    helper_editText.editText_FocusChange(editText, Browser_right.this);
    helper_main.grantPermissionsStorage(Browser_right.this);

    onNewIntent(getIntent());
}

From source file:de.baumann.browser.Browser_left.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    getWindow().setStatusBarColor(ContextCompat.getColor(Browser_left.this, R.color.colorPrimaryDark));

    WebView.enableSlowWholeDocumentDraw();
    setContentView(R.layout.activity_browser);
    helper_main.checkPin(Browser_left.this);
    helper_main.onStart(Browser_left.this);

    PreferenceManager.setDefaultValues(this, R.xml.user_settings, false);
    PreferenceManager.setDefaultValues(this, R.xml.user_settings_search, false);
    sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    sharedPref.edit().putBoolean("isOpened", true).apply();

    boolean show = sharedPref.getBoolean("introShowDo_notShow", true);

    if (show) {//from  w  w  w .ja  v a2 s.  c  o  m
        helper_main.switchToActivity(Browser_left.this, Activity_intro.class, "", false);
    }

    sharedPref.edit()
            .putString("openURL", sharedPref.getString("startURL", "https://github.com/scoute-dich/browser/"))
            .apply();
    sharedPref.edit().putInt("keyboard", 0).apply();
    sharedPref.getInt("keyboard", 0);

    if (sharedPref.getString("saved_key_ok", "no").equals("no")) {
        char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!$%&/()=?;:_-.,+#*<>"
                .toCharArray();
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 25; i++) {
            char c = chars[random.nextInt(chars.length)];
            sb.append(c);
        }
        sharedPref.edit().putString("saved_key", sb.toString()).apply();
        sharedPref.edit().putString("saved_key_ok", "yes").apply();
    }

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    actionBar = getSupportActionBar();

    customViewContainer = (FrameLayout) findViewById(R.id.customViewContainer);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    editText = (EditText) findViewById(R.id.editText);
    editText.setVisibility(View.GONE);
    editText.setHint(R.string.app_search_hint);
    editText.clearFocus();

    urlBar = (TextView) findViewById(R.id.urlBar);

    imageButton = (ImageButton) findViewById(R.id.imageButton);
    imageButton.setVisibility(View.INVISIBLE);
    imageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mWebView.scrollTo(0, 0);
            imageButton.setVisibility(View.INVISIBLE);
            if (!actionBar.isShowing()) {
                urlBar.setText(mWebView.getTitle());
                actionBar.show();
            }
            helper_browser.setNavArrows(mWebView, imageButton_left, imageButton_right);
        }
    });

    SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe);
    assert swipeView != null;
    swipeView.setColorSchemeResources(R.color.colorPrimary, R.color.colorAccent);
    swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mWebView.reload();
        }
    });

    mWebView = (ObservableWebView) findViewById(R.id.webView);
    if (sharedPref.getString("fullscreen", "2").equals("2")
            || sharedPref.getString("fullscreen", "2").equals("3")) {
        mWebView.setScrollViewCallbacks(this);
    }

    mWebChromeClient = new myWebChromeClient();
    mWebView.setWebChromeClient(mWebChromeClient);

    imageButton_left = (ImageButton) findViewById(R.id.imageButton_left);
    imageButton_right = (ImageButton) findViewById(R.id.imageButton_right);

    if (sharedPref.getBoolean("arrow", false)) {
        imageButton_left.setVisibility(View.VISIBLE);
        imageButton_right.setVisibility(View.VISIBLE);
    } else {
        imageButton_left.setVisibility(View.INVISIBLE);
        imageButton_right.setVisibility(View.INVISIBLE);
    }

    helper_webView.webView_Settings(Browser_left.this, mWebView);
    helper_webView.webView_WebViewClient(Browser_left.this, swipeView, mWebView, urlBar);

    mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);

    if (isNetworkUnAvailable()) {
        if (sharedPref.getBoolean("offline", false)) {
            if (isNetworkUnAvailable()) { // loading offline
                mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
                Snackbar.make(mWebView, R.string.toast_cache, Snackbar.LENGTH_SHORT).show();
            }
        } else {
            Snackbar.make(mWebView, R.string.toast_noInternet, Snackbar.LENGTH_SHORT).show();
        }
    }

    mWebView.setDownloadListener(new DownloadListener() {

        public void onDownloadStart(final String url, String userAgent, final String contentDisposition,
                final String mimetype, long contentLength) {

            registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

            final String filename = URLUtil.guessFileName(url, contentDisposition, mimetype);
            Snackbar snackbar = Snackbar
                    .make(mWebView, getString(R.string.toast_download_1) + " " + filename, Snackbar.LENGTH_LONG)
                    .setAction(getString(R.string.toast_yes), new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                            request.addRequestHeader("Cookie", CookieManager.getInstance().getCookie(url));
                            request.allowScanningByMediaScanner();
                            request.setNotificationVisibility(
                                    DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
                            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                                    filename);
                            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                            dm.enqueue(request);

                            Snackbar.make(mWebView, getString(R.string.toast_download) + " " + filename,
                                    Snackbar.LENGTH_SHORT).show();
                        }
                    });
            snackbar.show();
        }
    });

    helper_browser.toolbar(Browser_left.this, Browser_right.class, mWebView, toolbar);
    helper_editText.editText_EditorAction(editText, Browser_left.this, mWebView, urlBar);
    helper_editText.editText_FocusChange(editText, Browser_left.this);
    helper_main.grantPermissionsStorage(Browser_left.this);

    onNewIntent(getIntent());
}

From source file:mgks.os.webview.MainActivity.java

@SuppressLint({ "SetJavaScriptEnabled", "WrongViewCast" })
@Override//from   w w w .  j  a v a2s . c  o  m
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.w("READ_PERM = ", Manifest.permission.READ_EXTERNAL_STORAGE);
    Log.w("WRITE_PERM = ", Manifest.permission.WRITE_EXTERNAL_STORAGE);
    //Prevent the app from being started again when it is still alive in the background
    if (!isTaskRoot()) {
        finish();
        return;
    }

    setContentView(R.layout.activity_main);

    asw_view = findViewById(R.id.msw_view);

    final SwipeRefreshLayout pullfresh = findViewById(R.id.pullfresh);
    if (ASWP_PULLFRESH) {
        pullfresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pull_fresh();
                pullfresh.setRefreshing(false);
            }
        });
        asw_view.getViewTreeObserver()
                .addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
                    @Override
                    public void onScrollChanged() {
                        if (asw_view.getScrollY() == 0) {
                            pullfresh.setEnabled(true);
                        } else {
                            pullfresh.setEnabled(false);
                        }
                    }
                });
    } else {
        pullfresh.setRefreshing(false);
        pullfresh.setEnabled(false);
    }

    if (ASWP_PBAR) {
        asw_progress = findViewById(R.id.msw_progress);
    } else {
        findViewById(R.id.msw_progress).setVisibility(View.GONE);
    }
    asw_loading_text = findViewById(R.id.msw_loading_text);
    Handler handler = new Handler();

    //Launching app rating request
    if (ASWP_RATINGS) {
        handler.postDelayed(new Runnable() {
            public void run() {
                get_rating();
            }
        }, 1000 * 60); //running request after few moments
    }

    //Getting basic device information
    get_info();

    //Getting GPS location of device if given permission
    if (ASWP_LOCATION && !check_permission(1)) {
        ActivityCompat.requestPermissions(MainActivity.this,
                new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, loc_perm);
    }
    get_location();

    //Webview settings; defaults are customized for best performance
    WebSettings webSettings = asw_view.getSettings();

    if (!ASWP_OFFLINE) {
        webSettings.setJavaScriptEnabled(ASWP_JSCRIPT);
    }
    webSettings.setSaveFormData(ASWP_SFORM);
    webSettings.setSupportZoom(ASWP_ZOOM);
    webSettings.setGeolocationEnabled(ASWP_LOCATION);
    webSettings.setAllowFileAccess(true);
    webSettings.setAllowFileAccessFromFileURLs(true);
    webSettings.setAllowUniversalAccessFromFileURLs(true);
    webSettings.setUseWideViewPort(true);
    webSettings.setDomStorageEnabled(true);

    asw_view.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            return true;
        }
    });
    asw_view.setHapticFeedbackEnabled(false);

    asw_view.setDownloadListener(new DownloadListener() {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimeType,
                long contentLength) {

            if (!check_permission(2)) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[] {
                        Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE },
                        file_perm);
            } else {
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));

                request.setMimeType(mimeType);
                String cookies = CookieManager.getInstance().getCookie(url);
                request.addRequestHeader("cookie", cookies);
                request.addRequestHeader("User-Agent", userAgent);
                request.setDescription(getString(R.string.dl_downloading));
                request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                        URLUtil.guessFileName(url, contentDisposition, mimeType));
                DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                assert dm != null;
                dm.enqueue(request);
                Toast.makeText(getApplicationContext(), getString(R.string.dl_downloading2), Toast.LENGTH_LONG)
                        .show();
            }
        }
    });

    if (Build.VERSION.SDK_INT >= 21) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
        asw_view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
    } else if (Build.VERSION.SDK_INT >= 19) {
        asw_view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    }
    asw_view.setVerticalScrollBarEnabled(false);
    asw_view.setWebViewClient(new Callback());

    //Rendering the default URL
    aswm_view(ASWV_URL, false);

    asw_view.setWebChromeClient(new WebChromeClient() {
        //Handling input[type="file"] requests for android API 16+
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            if (ASWP_FUPLOAD) {
                asw_file_message = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType(ASWV_F_TYPE);
                if (ASWP_MULFILE) {
                    i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                }
                startActivityForResult(Intent.createChooser(i, getString(R.string.fl_chooser)), asw_file_req);
            }
        }

        //Handling input[type="file"] requests for android API 21+
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {
            if (check_permission(2) && check_permission(3)) {
                if (ASWP_FUPLOAD) {
                    if (asw_file_path != null) {
                        asw_file_path.onReceiveValue(null);
                    }
                    asw_file_path = filePathCallback;
                    Intent takePictureIntent = null;
                    if (ASWP_CAMUPLOAD) {
                        takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        if (takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null) {
                            File photoFile = null;
                            try {
                                photoFile = create_image();
                                takePictureIntent.putExtra("PhotoPath", asw_cam_message);
                            } catch (IOException ex) {
                                Log.e(TAG, "Image file creation failed", ex);
                            }
                            if (photoFile != null) {
                                asw_cam_message = "file:" + photoFile.getAbsolutePath();
                                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                            } else {
                                takePictureIntent = null;
                            }
                        }
                    }
                    Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
                    if (!ASWP_ONLYCAM) {
                        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
                        contentSelectionIntent.setType(ASWV_F_TYPE);
                        if (ASWP_MULFILE) {
                            contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
                        }
                    }
                    Intent[] intentArray;
                    if (takePictureIntent != null) {
                        intentArray = new Intent[] { takePictureIntent };
                    } else {
                        intentArray = new Intent[0];
                    }

                    Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
                    chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
                    chooserIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.fl_chooser));
                    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
                    startActivityForResult(chooserIntent, asw_file_req);
                }
                return true;
            } else {
                get_file();
                return false;
            }
        }

        //Getting webview rendering progress
        @Override
        public void onProgressChanged(WebView view, int p) {
            if (ASWP_PBAR) {
                asw_progress.setProgress(p);
                if (p == 100) {
                    asw_progress.setProgress(0);
                }
            }
        }

        // overload the geoLocations permissions prompt to always allow instantly as app permission was granted previously
        public void onGeolocationPermissionsShowPrompt(String origin,
                GeolocationPermissions.Callback callback) {
            if (Build.VERSION.SDK_INT < 23 || check_permission(1)) {
                // location permissions were granted previously so auto-approve
                callback.invoke(origin, true, false);
            } else {
                // location permissions not granted so request them
                ActivityCompat.requestPermissions(MainActivity.this,
                        new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, loc_perm);
            }
        }
    });
    if (getIntent().getData() != null) {
        String path = getIntent().getDataString();
        /*
        If you want to check or use specific directories or schemes or hosts
                
        Uri data        = getIntent().getData();
        String scheme   = data.getScheme();
        String host     = data.getHost();
        List<String> pr = data.getPathSegments();
        String param1   = pr.get(0);
        */
        aswm_view(path, false);
    }
}

From source file:org.mozilla.focus.fragment.BrowserFragment.java

/**
 * Use Android's Download Manager to queue this download.
 *///from  ww  w .j a  v  a 2s.  c om
private void queueDownload(Download download) {
    if (download == null) {
        return;
    }

    final Context context = getContext();
    if (context == null) {
        return;
    }

    final String cookie = CookieManager.getInstance().getCookie(download.getUrl());
    final String fileName = URLUtil.guessFileName(download.getUrl(), download.getContentDisposition(),
            download.getMimeType());

    final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(download.getUrl()))
            .addRequestHeader("User-Agent", download.getUserAgent()).addRequestHeader("Cookie", cookie)
            .addRequestHeader("Referer", getUrl())
            .setDestinationInExternalPublicDir(download.getDestinationDirectory(), fileName)
            .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
            .setMimeType(download.getMimeType());

    request.allowScanningByMediaScanner();

    final DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(request);
}

From source file:com.slarker.tech.hi0734.view.widget.webview.AdvancedWebView.java

@SuppressLint({ "SetJavaScriptEnabled" })
protected void init(Context context) {
    // in IDE's preview mode
    if (isInEditMode()) {
        // do not run the code from this method
        return;/*w w  w. java 2 s .c  o m*/
    }

    if (context instanceof Activity) {
        mActivity = new WeakReference<Activity>((Activity) context);
    }

    mLanguageIso3 = getLanguageIso3();

    setFocusable(true);
    setFocusableInTouchMode(true);

    setSaveEnabled(true);

    final String filesDir = context.getFilesDir().getPath();
    final String databaseDir = filesDir.substring(0, filesDir.lastIndexOf("/")) + DATABASES_SUB_FOLDER;

    final WebSettings webSettings = getSettings();
    webSettings.setAllowFileAccess(false);
    setAllowAccessFromFileUrls(webSettings, false);
    webSettings.setBuiltInZoomControls(false);
    webSettings.setUseWideViewPort(true);
    webSettings.setLoadWithOverviewMode(true);
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setUserAgentString(ApiClientHelper.getUserAgent((AppContext) x.app()) + "/isapp");
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
        // Hide the zoom controls for HONEYCOMB+
        webSettings.setDisplayZoomControls(false);
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(true);
    }
    if (Build.VERSION.SDK_INT < 18) {
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
    }
    webSettings.setDatabaseEnabled(true);
    if (Build.VERSION.SDK_INT < 19) {
        webSettings.setDatabasePath(databaseDir);
    }
    setMixedContentAllowed(webSettings, true);

    setThirdPartyCookiesEnabled(true);

    webSettings.setJavaScriptCanOpenWindowsAutomatically(true);

    super.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if (!hasError()) {
                if (mListener != null) {
                    mListener.onPageStarted(url, favicon);
                }
            }

            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onPageStarted(view, url, favicon);
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (!hasError()) {
                if (mListener != null) {
                    mListener.onPageFinished(url);
                }
            }

            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onPageFinished(view, url);
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            setLastError();

            if (mListener != null) {
                mListener.onPageError(errorCode, description, failingUrl);
            }

            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onReceivedError(view, errorCode, description, failingUrl);
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(final WebView view, final String url) {
            // if the hostname may not be accessed
            if (!isHostnameAllowed(url)) {
                // if a listener is available
                if (mListener != null) {
                    // inform the listener about the request
                    mListener.onExternalPageRequest(url);
                }

                // cancel the original request
                return true;
            }

            // if there is a user-specified handler available
            if (mCustomWebViewClient != null) {
                // if the user-specified handler asks to override the request
                if (mCustomWebViewClient.shouldOverrideUrlLoading(view, url)) {
                    // cancel the original request
                    return true;
                }
            }

            // route the request through the custom URL loading method
            view.loadUrl(url);

            // cancel the original request
            return true;
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onLoadResource(view, url);
            } else {
                super.onLoadResource(view, url);
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            if (Build.VERSION.SDK_INT >= 11) {
                if (mCustomWebViewClient != null) {
                    return mCustomWebViewClient.shouldInterceptRequest(view, url);
                } else {
                    return super.shouldInterceptRequest(view, url);
                }
            } else {
                return null;
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            if (Build.VERSION.SDK_INT >= 21) {
                if (mCustomWebViewClient != null) {
                    return mCustomWebViewClient.shouldInterceptRequest(view, request);
                } else {
                    return super.shouldInterceptRequest(view, request);
                }
            } else {
                return null;
            }
        }

        @Override
        public void onFormResubmission(WebView view, Message dontResend, Message resend) {
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onFormResubmission(view, dontResend, resend);
            } else {
                super.onFormResubmission(view, dontResend, resend);
            }
        }

        @Override
        public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.doUpdateVisitedHistory(view, url, isReload);
            } else {
                super.doUpdateVisitedHistory(view, url, isReload);
            }
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onReceivedSslError(view, handler, error);
            } else {
                super.onReceivedSslError(view, handler, error);
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public void onReceivedClientCertRequest(WebView view, ClientCertRequest request) {
            if (Build.VERSION.SDK_INT >= 21) {
                if (mCustomWebViewClient != null) {
                    mCustomWebViewClient.onReceivedClientCertRequest(view, request);
                } else {
                    super.onReceivedClientCertRequest(view, request);
                }
            }
        }

        @Override
        public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host,
                String realm) {
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onReceivedHttpAuthRequest(view, handler, host, realm);
            } else {
                super.onReceivedHttpAuthRequest(view, handler, host, realm);
            }
        }

        @Override
        public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
            if (mCustomWebViewClient != null) {
                return mCustomWebViewClient.shouldOverrideKeyEvent(view, event);
            } else {
                return super.shouldOverrideKeyEvent(view, event);
            }
        }

        @Override
        public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onUnhandledKeyEvent(view, event);
            } else {
                super.onUnhandledKeyEvent(view, event);
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        @TargetApi(21)
        public void onUnhandledInputEvent(WebView view, InputEvent event) {
            if (Build.VERSION.SDK_INT >= 21) {
                if (mCustomWebViewClient != null) {
                    //                        mCustomWebViewClient.onUnhandledInputEvent(view, event);
                } else {
                    //                        super.onUnhandledInputEvent(view, event);
                }
            }
        }

        @Override
        public void onScaleChanged(WebView view, float oldScale, float newScale) {
            if (mCustomWebViewClient != null) {
                mCustomWebViewClient.onScaleChanged(view, oldScale, newScale);
            } else {
                super.onScaleChanged(view, oldScale, newScale);
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public void onReceivedLoginRequest(WebView view, String realm, String account, String args) {
            if (Build.VERSION.SDK_INT >= 12) {
                if (mCustomWebViewClient != null) {
                    mCustomWebViewClient.onReceivedLoginRequest(view, realm, account, args);
                } else {
                    super.onReceivedLoginRequest(view, realm, account, args);
                }
            }
        }

    });

    super.setWebChromeClient(new WebChromeClient() {

        // file upload callback (Android 2.2 (API level 8) -- Android 2.3 (API level 10)) (hidden method)
        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            openFileChooser(uploadMsg, null);
        }

        // file upload callback (Android 3.0 (API level 11) -- Android 4.0 (API level 15)) (hidden method)
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            openFileChooser(uploadMsg, acceptType, null);
        }

        // file upload callback (Android 4.1 (API level 16) -- Android 4.3 (API level 18)) (hidden method)
        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileInput(uploadMsg, null, false);
        }

        // file upload callback (Android 5.0 (API level 21) -- current) (public method)
        @SuppressWarnings("all")
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {
            if (Build.VERSION.SDK_INT >= 21) {
                final boolean allowMultiple = fileChooserParams
                        .getMode() == FileChooserParams.MODE_OPEN_MULTIPLE;

                openFileInput(null, filePathCallback, allowMultiple);

                return true;
            } else {
                return false;
            }
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onProgressChanged(view, newProgress);
            } else {
                super.onProgressChanged(view, newProgress);
            }
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onReceivedTitle(view, title);
            } else {
                super.onReceivedTitle(view, title);
            }
        }

        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onReceivedIcon(view, icon);
            } else {
                super.onReceivedIcon(view, icon);
            }
        }

        @Override
        public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onReceivedTouchIconUrl(view, url, precomposed);
            } else {
                super.onReceivedTouchIconUrl(view, url, precomposed);
            }
        }

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onShowCustomView(view, callback);
            } else {
                super.onShowCustomView(view, callback);
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) {
            if (Build.VERSION.SDK_INT >= 14) {
                if (mCustomWebChromeClient != null) {
                    mCustomWebChromeClient.onShowCustomView(view, requestedOrientation, callback);
                } else {
                    super.onShowCustomView(view, requestedOrientation, callback);
                }
            }
        }

        @Override
        public void onHideCustomView() {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onHideCustomView();
            } else {
                super.onHideCustomView();
            }
        }

        @Override
        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture,
                Message resultMsg) {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
            } else {
                return super.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
            }
        }

        @Override
        public void onRequestFocus(WebView view) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onRequestFocus(view);
            } else {
                super.onRequestFocus(view);
            }
        }

        @Override
        public void onCloseWindow(WebView window) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onCloseWindow(window);
            } else {
                super.onCloseWindow(window);
            }
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.onJsAlert(view, url, message, result);
            } else {
                return super.onJsAlert(view, url, message, result);
            }
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.onJsConfirm(view, url, message, result);
            } else {
                return super.onJsConfirm(view, url, message, result);
            }
        }

        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue,
                JsPromptResult result) {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.onJsPrompt(view, url, message, defaultValue, result);
            } else {
                return super.onJsPrompt(view, url, message, defaultValue, result);
            }
        }

        @Override
        public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.onJsBeforeUnload(view, url, message, result);
            } else {
                return super.onJsBeforeUnload(view, url, message, result);
            }
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) {
            if (mGeolocationEnabled) {
                callback.invoke(origin, true, false);
            } else {
                if (mCustomWebChromeClient != null) {
                    mCustomWebChromeClient.onGeolocationPermissionsShowPrompt(origin, callback);
                } else {
                    super.onGeolocationPermissionsShowPrompt(origin, callback);
                }
            }
        }

        @Override
        public void onGeolocationPermissionsHidePrompt() {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onGeolocationPermissionsHidePrompt();
            } else {
                super.onGeolocationPermissionsHidePrompt();
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public void onPermissionRequest(PermissionRequest request) {
            if (Build.VERSION.SDK_INT >= 21) {
                if (mCustomWebChromeClient != null) {
                    mCustomWebChromeClient.onPermissionRequest(request);
                } else {
                    super.onPermissionRequest(request);
                }
            }
        }

        @SuppressLint("NewApi")
        @SuppressWarnings("all")
        public void onPermissionRequestCanceled(PermissionRequest request) {
            if (Build.VERSION.SDK_INT >= 21) {
                if (mCustomWebChromeClient != null) {
                    mCustomWebChromeClient.onPermissionRequestCanceled(request);
                } else {
                    super.onPermissionRequestCanceled(request);
                }
            }
        }

        @Override
        public boolean onJsTimeout() {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.onJsTimeout();
            } else {
                return super.onJsTimeout();
            }
        }

        @Override
        public void onConsoleMessage(String message, int lineNumber, String sourceID) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onConsoleMessage(message, lineNumber, sourceID);
            } else {
                super.onConsoleMessage(message, lineNumber, sourceID);
            }
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.onConsoleMessage(consoleMessage);
            } else {
                return super.onConsoleMessage(consoleMessage);
            }
        }

        @Override
        public Bitmap getDefaultVideoPoster() {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.getDefaultVideoPoster();
            } else {
                return super.getDefaultVideoPoster();
            }
        }

        @Override
        public View getVideoLoadingProgressView() {
            if (mCustomWebChromeClient != null) {
                return mCustomWebChromeClient.getVideoLoadingProgressView();
            } else {
                return super.getVideoLoadingProgressView();
            }
        }

        @Override
        public void getVisitedHistory(ValueCallback<String[]> callback) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.getVisitedHistory(callback);
            } else {
                super.getVisitedHistory(callback);
            }
        }

        @Override
        public void onExceededDatabaseQuota(String url, String databaseIdentifier, long quota,
                long estimatedDatabaseSize, long totalQuota, QuotaUpdater quotaUpdater) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onExceededDatabaseQuota(url, databaseIdentifier, quota,
                        estimatedDatabaseSize, totalQuota, quotaUpdater);
            } else {
                super.onExceededDatabaseQuota(url, databaseIdentifier, quota, estimatedDatabaseSize, totalQuota,
                        quotaUpdater);
            }
        }

        @Override
        public void onReachedMaxAppCacheSize(long requiredStorage, long quota, QuotaUpdater quotaUpdater) {
            if (mCustomWebChromeClient != null) {
                mCustomWebChromeClient.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater);
            } else {
                super.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater);
            }
        }

    });

    setDownloadListener(new DownloadListener() {

        @Override
        public void onDownloadStart(final String url, final String userAgent, final String contentDisposition,
                final String mimeType, final long contentLength) {
            final String suggestedFilename = URLUtil.guessFileName(url, contentDisposition, mimeType);

            if (mListener != null) {
                mListener.onDownloadRequested(url, suggestedFilename, mimeType, contentLength,
                        contentDisposition, userAgent);
            }
        }

    });
}