Example usage for android.webkit WebSettings setJavaScriptEnabled

List of usage examples for android.webkit WebSettings setJavaScriptEnabled

Introduction

In this page you can find the example usage for android.webkit WebSettings setJavaScriptEnabled.

Prototype

public abstract void setJavaScriptEnabled(boolean flag);

Source Link

Document

Tells the WebView to enable JavaScript execution.

Usage

From source file:com.mobicage.rogerthat.plugins.messaging.ServiceMessageDetailActivity.java

protected void updateMessageDetail(final boolean isUpdate) {
    T.UI();/*from   w ww  .ja  v a 2 s. c  om*/
    // Set sender avatar
    ImageView avatarImage = (ImageView) findViewById(R.id.avatar);
    String sender = mCurrentMessage.sender;
    setAvatar(avatarImage, sender);
    // Set sender name
    TextView senderView = (TextView) findViewById(R.id.sender);
    final String senderName = mFriendsPlugin.getName(sender);
    senderView.setText(senderName == null ? sender : senderName);
    // Set timestamp
    TextView timestampView = (TextView) findViewById(R.id.timestamp);
    timestampView.setText(TimeUtils.getDayTimeStr(this, mCurrentMessage.timestamp * 1000));

    // Set clickable region on top to go to friends detail
    final RelativeLayout messageHeader = (RelativeLayout) findViewById(R.id.message_header);
    messageHeader.setOnClickListener(getFriendDetailOnClickListener(mCurrentMessage.sender));
    messageHeader.setVisibility(View.VISIBLE);

    // Set message
    TextView messageView = (TextView) findViewById(R.id.message);
    WebView web = (WebView) findViewById(R.id.webview);
    FrameLayout flay = (FrameLayout) findViewById(R.id.message_details);
    Resources resources = getResources();
    flay.setBackgroundColor(resources.getColor(R.color.mc_background));
    boolean showBranded = false;

    int darkSchemeTextColor = resources.getColor(android.R.color.primary_text_dark);
    int lightSchemeTextColor = resources.getColor(android.R.color.primary_text_light);

    senderView.setTextColor(lightSchemeTextColor);
    timestampView.setTextColor(lightSchemeTextColor);

    BrandingResult br = null;
    if (!TextUtils.isEmptyOrWhitespace(mCurrentMessage.branding)) {
        boolean brandingAvailable = false;
        try {
            brandingAvailable = mMessagingPlugin.getBrandingMgr().isBrandingAvailable(mCurrentMessage.branding);
        } catch (BrandingFailureException e1) {
            L.d(e1);
        }
        try {
            if (brandingAvailable) {
                br = mMessagingPlugin.getBrandingMgr().prepareBranding(mCurrentMessage);
                WebSettings settings = web.getSettings();
                settings.setJavaScriptEnabled(false);
                settings.setBlockNetworkImage(false);
                web.loadUrl("file://" + br.file.getAbsolutePath());
                web.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
                if (br.color != null) {
                    flay.setBackgroundColor(br.color);
                }
                if (!br.showHeader) {
                    messageHeader.setVisibility(View.GONE);
                    MarginLayoutParams mlp = (MarginLayoutParams) web.getLayoutParams();
                    mlp.setMargins(0, 0, 0, mlp.bottomMargin);
                } else if (br.scheme == ColorScheme.dark) {
                    senderView.setTextColor(darkSchemeTextColor);
                    timestampView.setTextColor(darkSchemeTextColor);
                }

                showBranded = true;
            } else {
                mMessagingPlugin.getBrandingMgr().queueGenericBranding(mCurrentMessage.branding);
            }
        } catch (BrandingFailureException e) {
            L.bug("Could not display message with branding: branding is available, but prepareBranding failed",
                    e);
        }
    }

    if (showBranded) {
        web.setVisibility(View.VISIBLE);
        messageView.setVisibility(View.GONE);
    } else {
        web.setVisibility(View.GONE);
        messageView.setVisibility(View.VISIBLE);
        messageView.setText(mCurrentMessage.message);
    }

    // Add list of members who did not ack yet
    FlowLayout memberSummary = (FlowLayout) findViewById(R.id.member_summary);
    memberSummary.removeAllViews();
    SortedSet<MemberStatusTO> memberSummarySet = new TreeSet<MemberStatusTO>(getMemberstatusComparator());
    for (MemberStatusTO ms : mCurrentMessage.members) {
        if ((ms.status & MessagingPlugin.STATUS_ACKED) != MessagingPlugin.STATUS_ACKED
                && !ms.member.equals(mCurrentMessage.sender)) {
            memberSummarySet.add(ms);
        }
    }
    FlowLayout.LayoutParams flowLP = new FlowLayout.LayoutParams(2, 0);
    for (MemberStatusTO ms : memberSummarySet) {
        FrameLayout fl = new FrameLayout(this);
        fl.setLayoutParams(flowLP);
        memberSummary.addView(fl);
        fl.addView(createParticipantView(ms));
    }
    memberSummary.setVisibility(memberSummarySet.size() < 2 ? View.GONE : View.VISIBLE);

    // Add members statuses
    final LinearLayout members = (LinearLayout) findViewById(R.id.members);
    members.removeAllViews();
    final String myEmail = mService.getIdentityStore().getIdentity().getEmail();
    boolean isMember = false;
    mSomebodyAnswered = false;
    for (MemberStatusTO ms : mCurrentMessage.members) {
        boolean showMember = true;
        View view = getLayoutInflater().inflate(R.layout.message_member_detail, null);
        // Set receiver avatar
        RelativeLayout rl = (RelativeLayout) view.findViewById(R.id.avatar);
        rl.addView(createParticipantView(ms));
        // Set receiver name
        TextView receiverView = (TextView) view.findViewById(R.id.receiver);
        final String memberName = mFriendsPlugin.getName(ms.member);
        receiverView.setText(memberName == null ? sender : memberName);
        // Set received timestamp
        TextView receivedView = (TextView) view.findViewById(R.id.received_timestamp);
        if ((ms.status & MessagingPlugin.STATUS_RECEIVED) == MessagingPlugin.STATUS_RECEIVED) {
            final String humanTime = TimeUtils.getDayTimeStr(this, ms.received_timestamp * 1000);
            if (ms.member.equals(mCurrentMessage.sender))
                receivedView.setText(getString(R.string.sent_at, humanTime));
            else
                receivedView.setText(getString(R.string.received_at, humanTime));
        } else {
            receivedView.setText(R.string.not_yet_received);
        }
        // Set replied timestamp
        TextView repliedView = (TextView) view.findViewById(R.id.acked_timestamp);
        if ((ms.status & MessagingPlugin.STATUS_ACKED) == MessagingPlugin.STATUS_ACKED) {
            mSomebodyAnswered = true;
            String acked_timestamp = TimeUtils.getDayTimeStr(this, ms.acked_timestamp * 1000);
            if (ms.button_id != null) {

                ButtonTO button = null;
                for (ButtonTO b : mCurrentMessage.buttons) {
                    if (b.id.equals(ms.button_id)) {
                        button = b;
                        break;
                    }
                }
                if (button == null) {
                    repliedView.setText(getString(R.string.dismissed_at, acked_timestamp));
                    // Do not show sender as member if he hasn't clicked a
                    // button
                    showMember = !ms.member.equals(mCurrentMessage.sender);
                } else {
                    repliedView.setText(getString(R.string.replied_at, button.caption, acked_timestamp));
                }
            } else {
                if (ms.custom_reply == null) {
                    // Do not show sender as member if he hasn't clicked a
                    // button
                    showMember = !ms.member.equals(mCurrentMessage.sender);
                    repliedView.setText(getString(R.string.dismissed_at, acked_timestamp));
                } else
                    repliedView.setText(getString(R.string.replied_at, ms.custom_reply, acked_timestamp));
            }
        } else {
            repliedView.setText(R.string.not_yet_replied);
            showMember = !ms.member.equals(mCurrentMessage.sender);
        }
        if (br != null && br.scheme == ColorScheme.dark) {
            receiverView.setTextColor(darkSchemeTextColor);
            receivedView.setTextColor(darkSchemeTextColor);
            repliedView.setTextColor(darkSchemeTextColor);
        } else {
            receiverView.setTextColor(lightSchemeTextColor);
            receivedView.setTextColor(lightSchemeTextColor);
            repliedView.setTextColor(lightSchemeTextColor);
        }

        if (showMember)
            members.addView(view);
        isMember |= ms.member.equals(myEmail);
    }

    boolean isLocked = (mCurrentMessage.flags & MessagingPlugin.FLAG_LOCKED) == MessagingPlugin.FLAG_LOCKED;
    boolean canEdit = isMember && !isLocked;

    // Add attachments
    LinearLayout attachmentLayout = (LinearLayout) findViewById(R.id.attachment_layout);
    attachmentLayout.removeAllViews();
    if (mCurrentMessage.attachments.length > 0) {
        attachmentLayout.setVisibility(View.VISIBLE);

        for (final AttachmentTO attachment : mCurrentMessage.attachments) {
            View v = getLayoutInflater().inflate(R.layout.attachment_item, null);

            ImageView attachment_image = (ImageView) v.findViewById(R.id.attachment_image);
            if (AttachmentViewerActivity.CONTENT_TYPE_JPEG.equalsIgnoreCase(attachment.content_type)
                    || AttachmentViewerActivity.CONTENT_TYPE_PNG.equalsIgnoreCase(attachment.content_type)) {
                attachment_image.setImageResource(R.drawable.attachment_img);
            } else if (AttachmentViewerActivity.CONTENT_TYPE_PDF.equalsIgnoreCase(attachment.content_type)) {
                attachment_image.setImageResource(R.drawable.attachment_pdf);
            } else if (AttachmentViewerActivity.CONTENT_TYPE_VIDEO_MP4
                    .equalsIgnoreCase(attachment.content_type)) {
                attachment_image.setImageResource(R.drawable.attachment_video);
            } else {
                attachment_image.setImageResource(R.drawable.attachment_unknown);
                L.d("attachment.content_type not known: " + attachment.content_type);
            }

            TextView attachment_text = (TextView) v.findViewById(R.id.attachment_text);
            attachment_text.setText(attachment.name);

            v.setOnClickListener(new SafeViewOnClickListener() {

                @Override
                public void safeOnClick(View v) {
                    String downloadUrlHash = mMessagingPlugin
                            .attachmentDownloadUrlHash(attachment.download_url);

                    File attachmentsDir;
                    try {
                        attachmentsDir = mMessagingPlugin.attachmentsDir(mCurrentMessage.getThreadKey(), null);
                    } catch (IOException e) {
                        L.d("Unable to create attachment directory", e);
                        UIUtils.showAlertDialog(ServiceMessageDetailActivity.this, "",
                                R.string.unable_to_read_write_sd_card);
                        return;
                    }

                    boolean attachmentAvailable = mMessagingPlugin.attachmentExists(attachmentsDir,
                            downloadUrlHash);

                    if (!attachmentAvailable) {
                        try {
                            attachmentsDir = mMessagingPlugin.attachmentsDir(mCurrentMessage.getThreadKey(),
                                    mCurrentMessage.key);
                        } catch (IOException e) {
                            L.d("Unable to create attachment directory", e);
                            UIUtils.showAlertDialog(ServiceMessageDetailActivity.this, "",
                                    R.string.unable_to_read_write_sd_card);
                            return;
                        }

                        attachmentAvailable = mMessagingPlugin.attachmentExists(attachmentsDir,
                                downloadUrlHash);
                    }

                    if (!mService.getNetworkConnectivityManager().isConnected() && !attachmentAvailable) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(
                                ServiceMessageDetailActivity.this);
                        builder.setMessage(R.string.no_internet_connection_try_again);
                        builder.setPositiveButton(R.string.rogerthat, null);
                        AlertDialog dialog = builder.create();
                        dialog.show();
                        return;
                    }
                    if (IOUtils.shouldCheckExternalStorageAvailable()) {
                        String state = Environment.getExternalStorageState();
                        if (Environment.MEDIA_MOUNTED.equals(state)) {
                            // Its all oke
                        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
                            if (!attachmentAvailable) {
                                L.d("Unable to write to sd-card");
                                UIUtils.showAlertDialog(ServiceMessageDetailActivity.this, "",
                                        R.string.unable_to_read_write_sd_card);
                                return;
                            }
                        } else {
                            L.d("Unable to read or write to sd-card");
                            UIUtils.showAlertDialog(ServiceMessageDetailActivity.this, "",
                                    R.string.unable_to_read_write_sd_card);
                            return;
                        }
                    }

                    L.d("attachment.content_type: " + attachment.content_type);
                    L.d("attachment.download_url: " + attachment.download_url);
                    L.d("attachment.name: " + attachment.name);
                    L.d("attachment.size: " + attachment.size);

                    if (AttachmentViewerActivity.supportsContentType(attachment.content_type)) {
                        Intent i = new Intent(ServiceMessageDetailActivity.this,
                                AttachmentViewerActivity.class);
                        i.putExtra("thread_key", mCurrentMessage.getThreadKey());
                        i.putExtra("message", mCurrentMessage.key);
                        i.putExtra("content_type", attachment.content_type);
                        i.putExtra("download_url", attachment.download_url);
                        i.putExtra("name", attachment.name);
                        i.putExtra("download_url_hash", downloadUrlHash);

                        startActivity(i);
                    } else {
                        AlertDialog.Builder builder = new AlertDialog.Builder(
                                ServiceMessageDetailActivity.this);
                        builder.setMessage(getString(R.string.attachment_can_not_be_displayed_in_your_version,
                                getString(R.string.app_name)));
                        builder.setPositiveButton(R.string.rogerthat, null);
                        AlertDialog dialog = builder.create();
                        dialog.show();
                    }
                }

            });

            attachmentLayout.addView(v);
        }

    } else {
        attachmentLayout.setVisibility(View.GONE);
    }

    LinearLayout widgetLayout = (LinearLayout) findViewById(R.id.widget_layout);
    if (mCurrentMessage.form == null) {
        widgetLayout.setVisibility(View.GONE);
    } else {
        widgetLayout.setVisibility(View.VISIBLE);
        widgetLayout.setEnabled(canEdit);
        displayWidget(widgetLayout, br);
    }

    // Add buttons
    TableLayout tableLayout = (TableLayout) findViewById(R.id.buttons);
    tableLayout.removeAllViews();

    for (final ButtonTO button : mCurrentMessage.buttons) {
        addButton(senderName, myEmail, mSomebodyAnswered, canEdit, tableLayout, button);
    }
    if (mCurrentMessage.form == null && (mCurrentMessage.flags
            & MessagingPlugin.FLAG_ALLOW_DISMISS) == MessagingPlugin.FLAG_ALLOW_DISMISS) {
        ButtonTO button = new ButtonTO();
        button.caption = "Roger that!";
        addButton(senderName, myEmail, mSomebodyAnswered, canEdit, tableLayout, button);
    }

    if (mCurrentMessage.broadcast_type != null) {
        L.d("Show broadcast spam control");
        final RelativeLayout broadcastSpamControl = (RelativeLayout) findViewById(R.id.broadcast_spam_control);
        View broadcastSpamControlBorder = findViewById(R.id.broadcast_spam_control_border);
        final View broadcastSpamControlDivider = findViewById(R.id.broadcast_spam_control_divider);

        final LinearLayout broadcastSpamControlTextContainer = (LinearLayout) findViewById(
                R.id.broadcast_spam_control_text_container);
        TextView broadcastSpamControlText = (TextView) findViewById(R.id.broadcast_spam_control_text);

        final LinearLayout broadcastSpamControlSettingsContainer = (LinearLayout) findViewById(
                R.id.broadcast_spam_control_settings_container);
        TextView broadcastSpamControlSettingsText = (TextView) findViewById(
                R.id.broadcast_spam_control_settings_text);
        TextView broadcastSpamControlIcon = (TextView) findViewById(R.id.broadcast_spam_control_icon);
        broadcastSpamControlIcon.setTypeface(mFontAwesomeTypeFace);
        broadcastSpamControlIcon.setText(R.string.fa_bell);

        final FriendBroadcastInfo fbi = mFriendsPlugin.getFriendBroadcastFlowForMfr(mCurrentMessage.sender);
        if (fbi == null) {
            L.bug("BroadcastData was null for: " + mCurrentMessage.sender);
            collapseDetails(DETAIL_SECTIONS);
            return;
        }
        broadcastSpamControl.setVisibility(View.VISIBLE);

        broadcastSpamControlSettingsContainer.setOnClickListener(new SafeViewOnClickListener() {

            @Override
            public void safeOnClick(View v) {
                L.d("goto broadcast settings");

                PressMenuIconRequestTO request = new PressMenuIconRequestTO();
                request.coords = fbi.coords;
                request.static_flow_hash = fbi.staticFlowHash;
                request.hashed_tag = fbi.hashedTag;
                request.generation = fbi.generation;
                request.service = mCurrentMessage.sender;
                mContext = "MENU_" + UUID.randomUUID().toString();
                request.context = mContext;
                request.timestamp = System.currentTimeMillis() / 1000;

                showTransmitting(null);
                Map<String, Object> userInput = new HashMap<String, Object>();
                userInput.put("request", request.toJSONMap());
                userInput.put("func", "com.mobicage.api.services.pressMenuItem");

                MessageFlowRun mfr = new MessageFlowRun();
                mfr.staticFlowHash = fbi.staticFlowHash;
                try {
                    JsMfr.executeMfr(mfr, userInput, mService, true);
                } catch (EmptyStaticFlowException ex) {
                    completeTransmit(null);
                    AlertDialog.Builder builder = new AlertDialog.Builder(ServiceMessageDetailActivity.this);
                    builder.setMessage(ex.getMessage());
                    builder.setPositiveButton(R.string.rogerthat, null);
                    AlertDialog dialog = builder.create();
                    dialog.show();
                    return;
                }
            }

        });

        UIUtils.showHint(this, mService, HINT_BROADCAST, R.string.hint_broadcast,
                mCurrentMessage.broadcast_type, mFriendsPlugin.getName(mCurrentMessage.sender));

        broadcastSpamControlText
                .setText(getString(R.string.broadcast_subscribed_to, mCurrentMessage.broadcast_type));
        broadcastSpamControlSettingsText.setText(fbi.label);
        int ligthAlpha = 180;
        int darkAlpha = 70;
        int alpha = ligthAlpha;
        if (br != null && br.scheme == ColorScheme.dark) {
            broadcastSpamControlIcon.setTextColor(getResources().getColor(android.R.color.black));
            broadcastSpamControlBorder.setBackgroundColor(darkSchemeTextColor);
            broadcastSpamControlDivider.setBackgroundColor(darkSchemeTextColor);
            activity.setBackgroundColor(darkSchemeTextColor);
            broadcastSpamControlText.setTextColor(lightSchemeTextColor);
            broadcastSpamControlSettingsText.setTextColor(lightSchemeTextColor);
            int alpacolor = Color.argb(darkAlpha, Color.red(lightSchemeTextColor),
                    Color.green(lightSchemeTextColor), Color.blue(lightSchemeTextColor));
            broadcastSpamControl.setBackgroundColor(alpacolor);

            alpha = darkAlpha;
        } else {
            broadcastSpamControlIcon.setTextColor(getResources().getColor(android.R.color.white));
            broadcastSpamControlBorder.setBackgroundColor(lightSchemeTextColor);
            broadcastSpamControlDivider.setBackgroundColor(lightSchemeTextColor);
            activity.setBackgroundColor(lightSchemeTextColor);
            broadcastSpamControlText.setTextColor(darkSchemeTextColor);
            broadcastSpamControlSettingsText.setTextColor(darkSchemeTextColor);
            int alpacolor = Color.argb(darkAlpha, Color.red(darkSchemeTextColor),
                    Color.green(darkSchemeTextColor), Color.blue(darkSchemeTextColor));
            broadcastSpamControl.setBackgroundColor(alpacolor);
        }

        if (br != null && br.color != null) {
            int alphaColor = Color.argb(alpha, Color.red(br.color), Color.green(br.color),
                    Color.blue(br.color));
            broadcastSpamControl.setBackgroundColor(alphaColor);
        }

        mService.postOnUIHandler(new SafeRunnable() {

            @Override
            protected void safeRun() throws Exception {
                int maxHeight = broadcastSpamControl.getHeight();
                broadcastSpamControlDivider.getLayoutParams().height = maxHeight;
                broadcastSpamControlDivider.requestLayout();

                broadcastSpamControlSettingsContainer.getLayoutParams().height = maxHeight;
                broadcastSpamControlSettingsContainer.requestLayout();

                broadcastSpamControlTextContainer.getLayoutParams().height = maxHeight;
                broadcastSpamControlTextContainer.requestLayout();

                int broadcastSpamControlWidth = broadcastSpamControl.getWidth();
                android.view.ViewGroup.LayoutParams lp = broadcastSpamControlSettingsContainer
                        .getLayoutParams();
                lp.width = broadcastSpamControlWidth / 4;
                broadcastSpamControlSettingsContainer.setLayoutParams(lp);
            }
        });
    }

    if (!isUpdate)
        collapseDetails(DETAIL_SECTIONS);
}

From source file:com.creativtrendz.folio.ui.FolioWebViewScroll.java

@SuppressLint({ "SetJavaScriptEnabled" })
protected void init(Context context) {
    if (context instanceof Activity) {
        mActivity = new WeakReference<>((Activity) context);
    }/*from  w w w.  j  a va  2 s  .  c  o  m*/

    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.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(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);

    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(WebView view, String url) {
            if (isHostnameAllowed(url)) {
                return mCustomWebViewClient != null && mCustomWebViewClient.shouldOverrideUrlLoading(view, url);
            } else {
                if (mListener != null) {
                    mListener.onExternalPageRequest(url);
                }

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

        // file upload callback (Android 5.0 (API level 21) -- current) (public method)
        @SuppressWarnings("all")
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                WebChromeClient.FileChooserParams fileChooserParams) {
            openFileInput(null, filePathCallback);
            return true;
        }

        @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(String url, String userAgent, String contentDisposition, String mimetype,
                long contentLength) {
            if (mListener != null) {
                mListener.onDownloadRequested(url, userAgent, contentDisposition, mimetype, contentLength);
            }
        }

    });
}

From source file:com.android.mail.ui.ConversationViewFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.conversation_view, container, false);
    mConversationContainer = (ConversationContainer) rootView.findViewById(R.id.conversation_container);
    mConversationContainer.setAccountController(this);

    mTopmostOverlay = (ViewGroup) mConversationContainer.findViewById(R.id.conversation_topmost_overlay);
    mTopmostOverlay.setOnKeyListener(this);
    inflateSnapHeader(mTopmostOverlay, inflater);
    mConversationContainer.setupSnapHeader();

    setupNewMessageBar();//from w  w w  .  jav a  2  s. c o m

    mProgressController = new ConversationViewProgressController(this, getHandler());
    mProgressController.instantiateProgressIndicators(rootView);

    mWebView = (ConversationWebView) mConversationContainer.findViewById(R.id.conversation_webview);

    mWebView.addJavascriptInterface(mJsBridge, "mail");
    // On JB or newer, we use the 'webkitAnimationStart' DOM event to signal load complete
    // Below JB, try to speed up initial render by having the webview do supplemental draws to
    // custom a software canvas.
    // TODO(mindyp):
    //PAGE READINESS SIGNAL FOR JELLYBEAN AND NEWER
    // Notify the app on 'webkitAnimationStart' of a simple dummy element with a simple no-op
    // animation that immediately runs on page load. The app uses this as a signal that the
    // content is loaded and ready to draw, since WebView delays firing this event until the
    // layers are composited and everything is ready to draw.
    // This signal does not seem to be reliable, so just use the old method for now.
    final boolean isJBOrLater = Utils.isRunningJellybeanOrLater();
    final boolean isUserVisible = isUserVisible();
    mWebView.setUseSoftwareLayer(!isJBOrLater);
    mEnableContentReadySignal = isJBOrLater && isUserVisible;
    mWebView.onUserVisibilityChanged(isUserVisible);
    mWebView.setWebViewClient(mWebViewClient);
    final WebChromeClient wcc = new WebChromeClient() {
        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            if (consoleMessage.messageLevel() == ConsoleMessage.MessageLevel.ERROR) {
                LogUtils.e(LOG_TAG, "JS: %s (%s:%d) f=%s", consoleMessage.message(), consoleMessage.sourceId(),
                        consoleMessage.lineNumber(), ConversationViewFragment.this);
            } else {
                LogUtils.i(LOG_TAG, "JS: %s (%s:%d) f=%s", consoleMessage.message(), consoleMessage.sourceId(),
                        consoleMessage.lineNumber(), ConversationViewFragment.this);
            }
            return true;
        }
    };
    mWebView.setWebChromeClient(wcc);

    final WebSettings settings = mWebView.getSettings();

    final ScrollIndicatorsView scrollIndicators = (ScrollIndicatorsView) rootView
            .findViewById(R.id.scroll_indicators);
    scrollIndicators.setSourceView(mWebView);

    settings.setJavaScriptEnabled(true);

    ConversationViewUtils.setTextZoom(getResources(), settings);

    if (Utils.isRunningLOrLater()) {
        CookieManager.getInstance().setAcceptThirdPartyCookies(mWebView, true /* accept */);
    }

    mViewsCreated = true;
    mWebViewLoadedData = false;

    return rootView;
}

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;/*from w ww .j  av a2s  .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);
            }
        }

    });
}

From source file:android.webkit.cts.WebViewTest.java

public void testAndroidAssetQueryParam() {
    if (!NullWebViewUtils.isWebViewAvailable()) {
        return;/*  w w  w  . j a  va2s  . c  o  m*/
    }

    WebSettings settings = mOnUiThread.getSettings();
    settings.setJavaScriptEnabled(true);
    // test passing a parameter
    String fileUrl = TestHtmlConstants.getFileUrl(TestHtmlConstants.PARAM_ASSET_URL + "?val=SUCCESS");
    mOnUiThread.loadUrlAndWaitForCompletion(fileUrl);
    assertEquals("SUCCESS", mOnUiThread.getTitle());
}

From source file:android.webkit.cts.WebViewTest.java

public void testAndroidAssetAnchor() {
    if (!NullWebViewUtils.isWebViewAvailable()) {
        return;/*from  w  w  w  . j  a v a  2s .  c  o m*/
    }

    WebSettings settings = mOnUiThread.getSettings();
    settings.setJavaScriptEnabled(true);
    // test using an anchor
    String fileUrl = TestHtmlConstants.getFileUrl(TestHtmlConstants.ANCHOR_ASSET_URL + "#anchor");
    mOnUiThread.loadUrlAndWaitForCompletion(fileUrl);
    assertEquals("anchor", mOnUiThread.getTitle());
}

From source file:android.webkit.cts.WebViewTest.java

@UiThreadTest
public void testRemoveJavascriptInterface() throws Exception {
    if (!NullWebViewUtils.isWebViewAvailable()) {
        return;/*ww  w  .jav a  2 s  . c o m*/
    }

    WebSettings settings = mWebView.getSettings();
    settings.setJavaScriptEnabled(true);
    String setTitleToPropertyTypeHtml = "<html><head></head>"
            + "<body onload=\"document.title = typeof window.injectedObject;\"></body></html>";

    // Test that adding an object gives an object type.
    mWebView.addJavascriptInterface(new Object(), "injectedObject");
    mOnUiThread.loadDataAndWaitForCompletion(setTitleToPropertyTypeHtml, "text/html", null);
    assertEquals("object", mWebView.getTitle());

    // Test that reloading the page after removing the object leaves the property undefined.
    mWebView.removeJavascriptInterface("injectedObject");
    mOnUiThread.loadDataAndWaitForCompletion(setTitleToPropertyTypeHtml, "text/html", null);
    assertEquals("undefined", mWebView.getTitle());
}

From source file:android.webkit.cts.WebViewTest.java

@UiThreadTest
public void testAddJavascriptInterfaceNullObject() throws Exception {
    if (!NullWebViewUtils.isWebViewAvailable()) {
        return;//from w w w. j a  v  a 2s .c o m
    }

    WebSettings settings = mWebView.getSettings();
    settings.setJavaScriptEnabled(true);
    String setTitleToPropertyTypeHtml = "<html><head></head>"
            + "<body onload=\"document.title = typeof window.injectedObject;\"></body></html>";

    // Test that the property is initially undefined.
    mOnUiThread.loadDataAndWaitForCompletion(setTitleToPropertyTypeHtml, "text/html", null);
    assertEquals("undefined", mWebView.getTitle());

    // Test that adding a null object has no effect.
    mWebView.addJavascriptInterface(null, "injectedObject");
    mOnUiThread.loadDataAndWaitForCompletion(setTitleToPropertyTypeHtml, "text/html", null);
    assertEquals("undefined", mWebView.getTitle());

    // Test that adding an object gives an object type.
    final Object obj = new Object();
    mWebView.addJavascriptInterface(obj, "injectedObject");
    mOnUiThread.loadDataAndWaitForCompletion(setTitleToPropertyTypeHtml, "text/html", null);
    assertEquals("object", mWebView.getTitle());

    // Test that trying to replace with a null object has no effect.
    mWebView.addJavascriptInterface(null, "injectedObject");
    mOnUiThread.loadDataAndWaitForCompletion(setTitleToPropertyTypeHtml, "text/html", null);
    assertEquals("object", mWebView.getTitle());
}

From source file:android.webkit.cts.WebViewTest.java

public void testSetNetworkAvailable() throws Exception {
    if (!NullWebViewUtils.isWebViewAvailable()) {
        return;/*from www . java  2s.c o  m*/
    }
    WebSettings settings = mOnUiThread.getSettings();
    settings.setJavaScriptEnabled(true);
    startWebServer(false);

    String url = mWebServer.getAssetUrl(TestHtmlConstants.NETWORK_STATE_URL);
    mOnUiThread.loadUrlAndWaitForCompletion(url);
    assertEquals("ONLINE", mOnUiThread.getTitle());

    mOnUiThread.setNetworkAvailable(false);

    // Wait for the DOM to receive notification of the network state change.
    new PollingCheck(TEST_TIMEOUT) {
        @Override
        protected boolean check() {
            return mOnUiThread.getTitle().equals("OFFLINE");
        }
    }.run();

    mOnUiThread.setNetworkAvailable(true);

    // Wait for the DOM to receive notification of the network state change.
    new PollingCheck(TEST_TIMEOUT) {
        @Override
        protected boolean check() {
            return mOnUiThread.getTitle().equals("ONLINE");
        }
    }.run();
}