Example usage for android.webkit WebChromeClient WebChromeClient

List of usage examples for android.webkit WebChromeClient WebChromeClient

Introduction

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

Prototype

WebChromeClient

Source Link

Usage

From source file:com.jaspersoft.android.jaspermobile.activities.viewer.html.report.fragment.NodeWebViewFragment.java

private void setWebViewClient() {
    webView.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress) {
            // fade in
            if (progressBar.getAlpha() == 0) {
                ObjectAnimator.ofFloat(progressBar, "alpha", 0f, 1f).setDuration(500).start();
            }/*  www . j ava  2 s.  c  o  m*/
            // update value
            int maxProgress = progressBar.getMax();
            progressBar.setProgress((maxProgress / 100) * progress);
            // fade out
            if (progress == maxProgress) {
                mResourceLoaded = true;
                ObjectAnimator.ofFloat(progressBar, "alpha", 1f, 0f).setDuration(1000).start();
            }
        }
    });
}

From source file:com.brayanarias.alarmproject.activity.MainActivity.java

private void setupNavigationView() {
    navigationView = (NavigationView) findViewById(R.id.navigation);
    MenuItem item = navigationView.getMenu().findItem(actualItem);
    View nav_header = LayoutInflater.from(this).inflate(R.layout.nav_header, null);
    final NavigationView navigationView = (NavigationView) findViewById(R.id.navigation);
    navigationView.addHeaderView(nav_header);
    //salute/*from   ww w  . j  a v a 2  s  .  c  om*/
    String salute = AlarmUtilities.getSalute(getApplicationContext());
    TextView tvWellcome = (TextView) nav_header.findViewById(R.id.tvWellcome);
    tvWellcome.setText(salute);
    if (item != null) {
        item.setChecked(true);
    }
    navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem menuItem) {
            CharSequence title = menuItem.getTitle();
            closeDrawer();
            switch (menuItem.getItemId()) {
            case R.id.itMyAlarms:
                showFragment(R.id.itMyAlarms);
                actualItem = menuItem.getItemId();
                menuItem.setChecked(true);
                getSupportActionBar().setTitle(title);
                return true;
            case R.id.itAddAlarm:
                Calendar calendar = Calendar.getInstance();
                int hour = calendar.get(Calendar.HOUR_OF_DAY);
                int minute = calendar.get(Calendar.MINUTE);
                TimePickerDialog timePickerDialog = TimePickerDialog
                        .newInstance(new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute) {
                                Alarm alarm = AlarmUtilities.createDefaultAlarm();
                                String min = minute < 10 ? "0" + minute : "" + minute;
                                if (hourOfDay == 12) {
                                    alarm.setAmPm("PM");
                                    alarm.setHour(hourOfDay);
                                    alarm.setHourFormatted((hourOfDay) + ":" + min);
                                } else if (hourOfDay > 12) {
                                    alarm.setAmPm("PM");
                                    alarm.setHour(hourOfDay - 12);
                                    alarm.setHourFormatted((hourOfDay - 12) + ":" + min);
                                } else {
                                    if (hourOfDay == 0) {
                                        hourOfDay = 12;
                                    }
                                    alarm.setAmPm("AM");
                                    alarm.setHour(hourOfDay);
                                    alarm.setHourFormatted(hourOfDay + ":" + min);
                                }
                                alarm.setMinute(minute);
                                Intent intent = new Intent(getApplicationContext(), AddAlarmActivity.class);
                                intent.putExtra(Constant.actionAlarmKey, Constant.addAlarm);
                                intent.putExtra(Constant.alarmSerializableKey, alarm);
                                startActivity(intent);
                            }
                        }, hour, minute, false);
                timePickerDialog.show(getSupportFragmentManager(), "tag");
                return true;
            case R.id.itCurrentMonth:
                actualItem = menuItem.getItemId();
                menuItem.setChecked(true);
                showFragment(R.id.itCurrentMonth);
                getSupportActionBar().setTitle(title);
                return true;
            /*
            case R.id.itConfig:
                actualItem = menuItem.getItemId();
                menuItem.setChecked(true);
                showFragment(R.id.itConfig);
                getSupportActionBar().setTitle(title);
                closeDrawer();
                return true;
            */
            case R.id.itAbout:
                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(MainActivity.this);
                WebView wvLegal = (WebView) LayoutInflater.from(getApplication())
                        .inflate(R.layout.web_view_legal, null);
                wvLegal.loadData(getString(R.string.html_legal), "text/html", "UTF-8");
                wvLegal.setWebChromeClient(new WebChromeClient());
                alertBuilder.setView(wvLegal);
                alertBuilder.setTitle(R.string.txt_about_app);
                alertBuilder.setCancelable(true).setPositiveButton(getString(R.string.txt_button_ok),
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.dismiss();
                            }
                        });
                alertBuilder.show();
                return true;
            default:
                return false;
            }

        }
    });
}

From source file:edu.cmu.sv.trailscribe.view.MapsActivity.java

@SuppressLint("SetJavaScriptEnabled")
private void setMap() {
    mWebView = (WebView) findViewById(R.id.maps_webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.addJavascriptInterface(this, "android");
    mWebView.setWebChromeClient(new WebChromeClient());
    mWebView.getSettings().setUseWideViewPort(false);
    mWebView.setWebViewClient(new WebViewClient());

    //      Setting to give OpenLayers access to local KML files
    //      Sets whether JavaScript running in the context of a file scheme URL should be allowed to 
    //      access content from any origin.
    mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);

    mController = new MapsController();
    mWebView.loadUrl(mController.getURL());
}

From source file:com.danielme.android.webviewdemo.WebViewDemoActivity.java

@SuppressLint({ "SetJavaScriptEnabled", "NewApi" })
@Override//  w  w w  .j a  v  a  2s.com
public void onCreate(Bundle savedInstanceState) {
    setTitle("?");
    AndroidUtil.removeStrict();
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    historyStack = new LinkedList<Link>();
    webview = (WebView) findViewById(R.id.webkit);
    faviconImageView = (ImageView) findViewById(R.id.favicon);

    urlEditText = (EditText) findViewById(R.id.url);
    progressBar = (ProgressBar) findViewById(R.id.progressbar);
    stopButton = ((Button) findViewById(R.id.stopButton));
    //favicon, deprecated since Android 4.3 but it's still necesary O_O ?
    WebIconDatabase.getInstance().open(getDir("icons", MODE_PRIVATE).getPath());

    freeQuotaSwitch = (Switch) findViewById(R.id.freeQuotaSwitch);

    leftQuotaText = (TextView) findViewById(R.id.leftQuota);

    SharedPreferences settings = getSharedPreferences("setting", 0);

    userid = settings.getString("userid", "123");
    tenantid = Integer.parseInt(settings.getString("tenantid", "3"));

    // check balance
    long balance = updateLeftQuota();

    freeQuotaSwitch.setChecked(balance > 0);
    tmMgr = new TMManager();

    // javascript and zoom
    webview.getSettings().setJavaScriptEnabled(true);
    webview.getSettings().setBuiltInZoomControls(true);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
        webview.getSettings().setPluginState(PluginState.ON);
    } else {
        //IMPORTANT!! this method is no longer available since Android 4.3
        //so the code doesn't compile anymore
        //webview.getSettings().setPluginsEnabled(true);
    }

    // downloads
    // webview.setDownloadListener(new CustomDownloadListener());

    webview.setWebViewClient(new CustomWebViewClient());

    webview.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int progress) {
            progressBar.setProgress(0);
            FrameLayout progressBarLayout = (FrameLayout) findViewById(R.id.progressBarLayout);
            progressBarLayout.setVisibility(View.VISIBLE);
            WebViewDemoActivity.this.setProgress(progress * 1000);

            TextView progressStatus = (TextView) findViewById(R.id.progressStatus);
            progressStatus.setText(progress + " %");
            progressBar.incrementProgressBy(progress);

            if (progress == 100) {
                progressBarLayout.setVisibility(View.GONE);
            }
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            WebViewDemoActivity.this.setTitle(
                    getString(R.string.app_name) + " - " + WebViewDemoActivity.this.webview.getTitle());
            for (Link link : historyStack) {
                if (link.getUrl().equals(WebViewDemoActivity.this.webview.getUrl())) {
                    link.setTitle(title);
                }
            }
        }

        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {
            faviconImageView.setImageBitmap(icon);
            view.getUrl();
            boolean b = false;
            ListIterator<Link> listIterator = historyStack.listIterator();
            while (!b && listIterator.hasNext()) {
                Link link = listIterator.next();
                if (link.getUrl().equals(view.getUrl())) {
                    link.setFavicon(icon);
                    b = true;
                }
            }
        }

    });

    //http://stackoverflow.com/questions/2083909/android-webview-refusing-user-input
    webview.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_UP:
                if (!v.hasFocus()) {
                    v.requestFocus();
                }
                break;
            }
            return false;
        }

    });

}

From source file:net.wequick.small.webkit.WebView.java

private void initSettings() {
    WebSettings webSettings = this.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setUserAgentString(webSettings.getUserAgentString() + " Native");
    this.addJavascriptInterface(new SmallJsBridge(), "_Small");

    this.setWebChromeClient(new WebChromeClient() {
        @Override/* www .ja v a2  s.  c om*/
        public void onReceivedTitle(android.webkit.WebView view, String title) {
            // Call if html title is set
            super.onReceivedTitle(view, title);
            mTitle = title;
            WebActivity activity = (WebActivity) WebViewPool.getContext(view);
            if (activity != null) {
                activity.setTitle(title);
            }
            // May receive head meta at the same time
            initMetas();
        }

        @Override
        public boolean onJsAlert(android.webkit.WebView view, String url, String message,
                final android.webkit.JsResult result) {
            Context context = WebViewPool.getContext(view);
            if (context == null)
                return false;

            AlertDialog.Builder dlg = new AlertDialog.Builder(context);
            dlg.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mConfirmed = true;
                    result.confirm();
                }
            });
            dlg.setMessage(message);
            AlertDialog alert = dlg.create();
            alert.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (!mConfirmed) {
                        result.cancel();
                    }
                }
            });
            mConfirmed = false;
            alert.show();
            return true;
        }

        @Override
        public boolean onJsConfirm(android.webkit.WebView view, String url, String message,
                final android.webkit.JsResult result) {
            Context context = WebViewPool.getContext(view);
            AlertDialog.Builder dlg = new AlertDialog.Builder(context);
            dlg.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mConfirmed = true;
                    result.confirm();
                }
            });
            dlg.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mConfirmed = true;
                    result.cancel();
                }
            });
            dlg.setMessage(message);
            AlertDialog alert = dlg.create();
            alert.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    if (!mConfirmed) {
                        result.cancel();
                    }
                }
            });
            mConfirmed = false;
            alert.show();
            return true;
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            String msg = consoleMessage.message();
            if (msg == null)
                return false;
            Uri uri = Uri.parse(msg);
            if (uri != null && null != uri.getScheme() && uri.getScheme().equals(SMALL_SCHEME)) {
                String host = uri.getHost();
                String ret = uri.getQueryParameter(SMALL_QUERY_KEY_RET);
                if (host.equals(SMALL_HOST_POP)) {
                    WebActivity activity = (WebActivity) WebViewPool.getContext(WebView.this);
                    activity.finish(ret);
                } else if (host.equals(SMALL_HOST_EXEC)) {
                    if (mOnResultListener != null) {
                        mOnResultListener.onResult(ret);
                    }
                }
                return true;
            }
            Log.d(consoleMessage.sourceId(),
                    "line" + consoleMessage.lineNumber() + ": " + consoleMessage.message());
            return true;
        }

        @Override
        public void onCloseWindow(android.webkit.WebView window) {
            super.onCloseWindow(window);
            close(new OnResultListener() {
                @Override
                public void onResult(String ret) {
                    if (ret.equals("false"))
                        return;

                    WebActivity activity = (WebActivity) WebViewPool.getContext(WebView.this);
                    activity.finish(ret);
                }
            });
        }
    });

    this.setWebViewClient(new android.webkit.WebViewClient() {

        private final String ANCHOR_SCHEME = "anchor";

        @Override
        public boolean shouldOverrideUrlLoading(android.webkit.WebView view, String url) {
            if (mLoadingUrl != null && mLoadingUrl.equals(url)) {
                // reload by window.location.reload or something
                return super.shouldOverrideUrlLoading(view, url);
            }

            Boolean hasStarted = mHasStartedUrl.get(url);
            if (hasStarted != null && hasStarted) {
                // location redirected before page finished
                return super.shouldOverrideUrlLoading(view, url);
            }

            HitTestResult hit = view.getHitTestResult();
            if (hit != null) {
                Uri uri = Uri.parse(url);
                if (uri.getScheme().equals(ANCHOR_SCHEME)) {
                    // Scroll to anchor
                    int anchorY = Integer.parseInt(uri.getHost());
                    view.scrollTo(0, anchorY);
                } else {
                    Small.openUri(uri, WebViewPool.getContext(view));
                }
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onPageStarted(android.webkit.WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            mHasStartedUrl.put(url, true);

            if (mLoadingUrl != null && mLoadingUrl.equals(url)) {
                // reload by window.location.reload or something
                mInjected = false;
            }
            if (sWebViewClient != null && url.equals(mLoadingUrl)) {
                sWebViewClient.onPageStarted(WebViewPool.getContext(view), (WebView) view, url, favicon);
            }
        }

        @Override
        public void onPageFinished(android.webkit.WebView view, String url) {
            super.onPageFinished(view, url);
            mHasStartedUrl.remove(url);

            HitTestResult hit = view.getHitTestResult();
            if (hit != null && hit.getType() == HitTestResult.SRC_ANCHOR_TYPE) {
                // Triggered by user clicked
                Uri uri = Uri.parse(url);
                String anchor = uri.getFragment();
                if (anchor != null) {
                    // If is an anchor, calculate the content offset by DOM
                    // and call native to adjust WebView's offset
                    view.loadUrl(JS_PREFIX + "var y=document.body.scrollTop;"
                            + "var e=document.getElementsByName('" + anchor + "')[0];" + "while(e){"
                            + "y+=e.offsetTop-e.scrollTop+e.clientTop;e=e.offsetParent;}" + "location='"
                            + ANCHOR_SCHEME + "://'+y;");
                }
            }

            if (!mInjected) {
                // Re-inject Small Js
                loadJs(SMALL_INJECT_JS);
                initMetas();
                mInjected = true;
            }

            if (sWebViewClient != null && url.equals(mLoadingUrl)) {
                sWebViewClient.onPageFinished(WebViewPool.getContext(view), (WebView) view, url);
            }
        }

        @Override
        public void onReceivedError(android.webkit.WebView view, int errorCode, String description,
                String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            Log.e("Web", "error: " + description);
            if (sWebViewClient != null && failingUrl.equals(mLoadingUrl)) {
                sWebViewClient.onReceivedError(WebViewPool.getContext(view), (WebView) view, errorCode,
                        description, failingUrl);
            }
        }
    });
}

From source file:com.google.android.apps.paco.FeedbackActivity.java

private void setWebChromeClientThatHandlesAlertsAsDialogs() {
    webView.setWebChromeClient(new WebChromeClient() {
        @Override/*  w  ww .jav  a  2s.c  o m*/
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {

            new AlertDialog.Builder(view.getContext()).setMessage(message).setCancelable(true)
                    .setPositiveButton(R.string.ok, new Dialog.OnClickListener() {

                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }

                    }).create().show();
            result.confirm();
            return true;
        }

        public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
            if (url.contains("file:///android_asset/map.html")) {
                if (showDialog == false) {
                    result.confirm();
                    return true;
                } else {
                    new AlertDialog.Builder(view.getContext()).setMessage(message).setCancelable(true)
                            .setPositiveButton(R.string.ok, new Dialog.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    showDialog = false;
                                    dialog.dismiss();
                                    result.confirm();
                                }
                            }).setNegativeButton(R.string.cancel_button, new Dialog.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    result.cancel();
                                }
                            }).create().show();
                    return true;
                }
            }
            return super.onJsConfirm(view, url, message, result);
        }

        @Override
        public void onConsoleMessage(String message, int lineNumber, String sourceID) {
            Log.d(PacoConstants.TAG, message + " -- From line " + lineNumber + " of " + sourceID);
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            Log.d(PacoConstants.TAG, "*" + consoleMessage.message() + " -- From line "
                    + consoleMessage.lineNumber() + " of " + consoleMessage.sourceId());
            return true;
        }

    });
}

From source file:id.zelory.codepolitan.ui.fragment.ReadFragment.java

@SuppressLint("SetJavaScriptEnabled")
private void setupWebView() {
    content.setWebChromeClient(new WebChromeClient());
    content.getSettings().setJavaScriptEnabled(true);
    content.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
}

From source file:com.pdftron.pdf.controls.ReflowPagerAdapter.java

public void initialize() {
    // set loading file depending on night mode
    if (sIsNightMode) {
        mLoadingFile = NIGHT_MODE_LOADING_FILE;
    } else {//from  w  w w . j  a va 2  s. c  o  m
        mLoadingFile = NORMAL_MODE_LOADING_FILE;
    }

    if (mWebViewRepository != null) {
        mWebViewRepository.reset();
    }

    ReflowWebView[] webViews = mWebViewRepository.getWebViews();
    for (final ReflowWebView webView : webViews) {
        webView.clearCache(true); // reset reading css file
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWillNotCacheDrawing(false);
        if (sIsNightMode) {
            webView.setBackgroundColor(Color.BLACK);
        } else {
            webView.setBackgroundColor(Color.WHITE);
        }
        webView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        webView.loadUrl("about:blank");
        webView.setListener(this);

        webView.setWebChromeClient(new WebChromeClient()); // enable the use of methods like alert in javascript
        webView.setWebViewClient(new WebViewClient() {
            // now all links the user clicks load in your WebView
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                Log.e(TAG, description + " url: " + failingUrl);
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                super.onReceivedSslError(view, handler, error);
                Log.e(TAG, error.toString());
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("file:///") && url.endsWith(".html")) {
                    int slashPos = url.lastIndexOf('/');
                    try {
                        int objNum = Integer.parseInt(url.substring(slashPos + 1, url.length() - 5));
                        int pageNum = 0;
                        for (int i = 1; i <= mPageCount; i++) {
                            try {
                                Page page = mDoc.getPage(i);
                                if (page.getSDFObj().getObjNum() == objNum) {
                                    pageNum = i;
                                    break;
                                }
                            } catch (Exception e) {
                            }
                        }
                        if (pageNum != 0) {
                            mViewPager.setCurrentItem(pageNum - 1);
                        }
                    } catch (NumberFormatException e) {
                        return true;
                    }
                } else {
                    if (url.startsWith("mailto:")
                            || android.util.Patterns.EMAIL_ADDRESS.matcher(url).matches()) {
                        if (url.startsWith("mailto:")) {
                            url = url.substring(7);
                        }
                        Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", url, null));
                        mContext.startActivity(Intent.createChooser(intent,
                                mContext.getResources().getString(R.string.tools_misc_sendemail)));
                    } else {
                        // ACTION_VIEW needs the address to have http or https
                        if (!url.startsWith("https://") && !url.startsWith("http://")) {
                            url = "http://" + url;
                        }
                        if (DEBUG)
                            Log.d(TAG, url);
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        mContext.startActivity(Intent.createChooser(intent,
                                mContext.getResources().getString(R.string.tools_misc_openwith)));
                    }
                }
                return true;
            }
        });
    }
}

From source file:com.scoreflex.ScoreflexView.java

/**
 * The constructor of the view.//w ww  . j a v a 2s. co m
 * @param activity The activity holding the view.
 * @param attrs
 * @param defStyle
 */
@SuppressWarnings("deprecation")
public ScoreflexView(Activity activity, AttributeSet attrs, int defStyle) {
    super(activity, attrs, defStyle);

    // Keep a reference on the activity
    mParentActivity = activity;

    // Default layout params
    if (null == getLayoutParams()) {
        setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                Scoreflex.getDensityIndependantPixel(R.dimen.scoreflex_panel_height)));
    }

    // Set our background color
    setBackgroundColor(getContext().getResources().getColor(R.color.scoreflex_background_color));

    // Create the top bar
    View topBar = new View(getContext());
    topBar.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            getResources().getDimensionPixelSize(R.dimen.scoreflex_topbar_height), Gravity.TOP));
    topBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.scoreflex_gradient_background));
    addView(topBar);

    // Create the retry button
    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    mErrorLayout = (ViewGroup) inflater.inflate(R.layout.scoreflex_error_layout, null);
    if (mErrorLayout != null) {

        // Configure refresh button
        Button refreshButton = (Button) mErrorLayout.findViewById(R.id.scoreflex_retry_button);
        if (null != refreshButton) {
            refreshButton.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    if (null == Scoreflex.getPlayerId()) {
                        setUserInterfaceState(new LoadingState());
                        loadUrlAfterLoggedIn(mInitialResource, mInitialRequestParams);
                    } else if (null == mWebView.getUrl()) {
                        setResource(mInitialResource);
                    } else {
                        mWebView.reload();
                    }
                }
            });
        }

        // Configure cancel button
        Button cancelButton = (Button) mErrorLayout.findViewById(R.id.scoreflex_cancel_button);
        if (null != cancelButton) {
            cancelButton.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    close();
                }
            });
        }

        // Get hold of the message view
        mMessageView = (TextView) mErrorLayout.findViewById(R.id.scoreflex_error_message_view);
        addView(mErrorLayout);

    }

    // Create the close button
    mCloseButton = new ImageButton(getContext());
    Drawable closeButtonDrawable = getResources().getDrawable(R.drawable.scoreflex_close_button);
    int closeButtonMargin = (int) ((getResources().getDimensionPixelSize(R.dimen.scoreflex_topbar_height)
            - closeButtonDrawable.getIntrinsicHeight()) / 2.0f);
    FrameLayout.LayoutParams closeButtonLayoutParams = new FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT,
            Gravity.TOP | Gravity.RIGHT);
    closeButtonLayoutParams.setMargins(0, closeButtonMargin, closeButtonMargin, 0);
    mCloseButton.setLayoutParams(closeButtonLayoutParams);
    mCloseButton.setImageDrawable(closeButtonDrawable);
    mCloseButton.setBackgroundDrawable(null);
    mCloseButton.setPadding(0, 0, 0, 0);
    mCloseButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            close();
        }
    });
    addView(mCloseButton);

    // Create the web view
    mWebView = new WebView(mParentActivity);
    mWebView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT));
    // mWebView.setBackgroundColor(Color.RED);
    mWebView.setWebViewClient(new ScoreflexWebViewClient());
    mWebView.setWebChromeClient(new WebChromeClient() {

        @Override
        public boolean onConsoleMessage(ConsoleMessage cm) {
            Log.d("Scoreflex", "javascript Error: "
                    + String.format("%s @ %d: %s", cm.message(), cm.lineNumber(), cm.sourceId()));
            return true;
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            // mtbActivity.mUploadMessage = uploadMsg;
            mUploadMessage = uploadMsg;

            String fileName = "picture.jpg";
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.TITLE, fileName);
            // mOutputFileUri = mParentActivity.getContentResolver().insert(
            // MediaStore.Images.Media.DATA, values);
            final List<Intent> cameraIntents = new ArrayList<Intent>();
            final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            final PackageManager packageManager = mParentActivity.getPackageManager();
            final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
            for (ResolveInfo res : listCam) {
                final String packageName = res.activityInfo.packageName;
                final Intent intent = new Intent(captureIntent);
                intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
                intent.setPackage(packageName);
                cameraIntents.add(intent);
            }

            // Filesystem.
            final Intent galleryIntent = new Intent();
            galleryIntent.setType("image/*");
            galleryIntent.setAction(Intent.ACTION_GET_CONTENT);

            // Chooser of filesystem options.
            final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source please");

            // Add the camera options.
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[] {}));

            mParentActivity.startActivityForResult(chooserIntent, Scoreflex.FILECHOOSER_RESULTCODE);
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            openFileChooser(uploadMsg);
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileChooser(uploadMsg);
        }
    });
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setDomStorageEnabled(true);
    mWebView.getSettings().setDatabasePath(
            getContext().getFilesDir().getPath() + "/data/" + getContext().getPackageName() + "/databases/");
    addView(mWebView);

    TypedArray a = mParentActivity.obtainStyledAttributes(attrs, R.styleable.ScoreflexView, defStyle, 0);
    String resource = a.getString(R.styleable.ScoreflexView_resource);
    if (null != resource)
        setResource(resource);

    a.recycle();

    // Create the animated spinner

    mProgressBar = (ProgressBar) ((LayoutInflater) getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.scoreflex_progress_bar, null);
    mProgressBar.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER));
    addView(mProgressBar);
    LocalBroadcastManager.getInstance(activity).registerReceiver(mLoginReceiver,
            new IntentFilter(Scoreflex.INTENT_USER_LOGED_IN));
    setUserInterfaceState(new InitialState());
}

From source file:fiskinfoo.no.sintef.fiskinfoo.MapFragment.java

@SuppressLint({ "SetJavaScriptEnabled" })
private void configureWebParametersAndLoadDefaultMapApplication() {
    if (getView() == null) {
        throw new NullPointerException();
    }//from w  w w .  j  av  a  2  s  .  co m
    browser = (WebView) getView().findViewById(R.id.map_fragment_web_view);
    browser.getSettings().setJavaScriptEnabled(true);
    browser.getSettings().setDomStorageEnabled(true);
    browser.getSettings().setGeolocationEnabled(true);
    browser.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

    browser.addJavascriptInterface(new JavaScriptInterface(getActivity()), "Android");
    browser.setWebViewClient(new barentswatchFiskInfoWebClient());
    browser.setWebChromeClient(new WebChromeClient() {

        public void onGeolocationPermissionsShowPrompt(String origin,
                GeolocationPermissions.Callback callback) {
            Log.d("geolocation permission", "permission >>>" + origin);
            callback.invoke(origin, true, false);
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            Log.d(TAG, message);
            return super.onJsAlert(view, url, message, result);
        }

    });

    updateMap();
}