Example usage for android.webkit WebView setWebViewClient

List of usage examples for android.webkit WebView setWebViewClient

Introduction

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

Prototype

public void setWebViewClient(WebViewClient client) 

Source Link

Document

Sets the WebViewClient that will receive various notifications and requests.

Usage

From source file:justforcommunity.radiocom.fragments.HomePageFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragment_home, container, false);

    mActivity = (Home) getActivity();//  w  w  w.  j a  va  2  s .  c o m
    mContext = getContext();

    try {
        station.getHistory().replace("<body",
                "<body style=\'text-align:justify;color:gray;background-color:black;\'");
        station.getHistory().replaceAll("style=\".+?\"", "");

    } catch (Exception e) {

    }

    WebView wb = (WebView) v.findViewById(R.id.history_frame);
    wb.setBackgroundColor(Color.WHITE);

    // String fontscript = "<style>@font-face {font-family : 'HelveticaNeue-Light';src:url('file:///android_asset/fonts/"+VariablesGlobalesActivity.GENERICFONT+"');}</style>";
    String fontscript = "";
    String script = "<style type='text/css' >p{width:100%;}img{width:100%;height:auto;-webkit-transform: translate3d(0px,0px,0px);}a,h1,h2,h3,h4,h5,h6{color:"
            + GlobalValues.colorHTML
            + ";}div,p,span,a {max-width: 100%;}iframe{width:100%;height:auto;}</style>";

    wb.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        }
    });

    wb.loadDataWithBaseURL("",
            "<html><head>" + fontscript + script + "</head><body style=\"font-family:HelveticaNeue-Light; \">"
                    + station.getHistory() + "</body></html>",
            "text/html", "utf-8", "");

    wb.getSettings().setDomStorageEnabled(true);
    wb.getSettings().setJavaScriptEnabled(true);

    App application = (App) getActivity().getApplication();
    Tracker mTracker = application.getDefaultTracker();
    mTracker.setScreenName(getString(R.string.home_view));
    mTracker.send(new HitBuilders.ScreenViewBuilder().build());

    return v;
}

From source file:com.btmura.android.reddit.app.LinkFragment.java

@SuppressLint("SetJavaScriptEnabled")
private void setupWebView(WebView webView) {
    WebSettings settings = webView.getSettings();
    settings.setBuiltInZoomControls(true);
    settings.setDisplayZoomControls(false);
    settings.setDomStorageEnabled(true);
    settings.setJavaScriptEnabled(true);
    settings.setLoadWithOverviewMode(true);
    settings.setSupportZoom(true);//from   w ww.j  a v a 2s  .  c  om
    settings.setPluginState(PluginState.ON_DEMAND);
    settings.setUseWideViewPort(true);

    webView.setOnLongClickListener(this);

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if (progress != null) {
                progress.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (progress != null) {
                progress.setVisibility(View.GONE);
            }
        }
    });

    webView.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (progress != null) {
                progress.setProgress(newProgress);
            }
        }
    });
}

From source file:at.alladin.rmbt.android.help.RMBTHelpFragment.java

/**
* 
*///from   w  w w .  ja v  a2s  . c o m
@SuppressLint("SetJavaScriptEnabled")
@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {

    super.onCreateView(inflater, container, savedInstanceState);

    final Bundle args = getArguments();

    String url = args.getString(ARG_URL);

    if (url == null || url.length() == 0)
        url = this.getString(R.string.url_help);

    final Activity activity = getActivity();

    final WebView webview = new WebView(activity) {
        @Override
        public boolean onKeyDown(final int keyCode, final KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && canGoBack()) {
                goBack();
                return true;
            }
            return super.onKeyDown(keyCode, event);
        }
    };

    final WebSettings webSettings = webview.getSettings();
    final String userAgent = AppConstants.getUserAgentString(getActivity());
    if (userAgent != null) {
        webSettings.setUserAgentString(userAgent);
    }
    webSettings.setJavaScriptEnabled(true);

    webview.setWebViewClient(new WebViewClient() {
        @Override
        public void onReceivedError(final WebView view, final int errorCode, final String description,
                final String failingUrl) {
            Log.w(getTag(), "error code:" + errorCode);
            Log.d(getTag(), "error desc:" + description);
            Log.d(getTag(), "error url:" + failingUrl);
            webview.loadUrl("file:///android_res/raw/error.html");
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
    });

    if (!url.matches("^https?://.*")) {
        final String protocol = ConfigHelper.isControlSeverSSL(activity) ? "https" : "http";
        url = protocol + "://" + url;
    }

    webview.loadUrl(url);

    return webview;
}

From source file:com.nestlabs.sdk.NestAuthActivity.java

@Override
@SuppressLint("SetJavaScriptEnabled")
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.nest_auth_webview_layout);

    WebView clientWebView = (WebView) findViewById(R.id.auth_webview);
    mProgressBar = (ProgressBar) findViewById(R.id.webview_progress);
    mNestConfig = getIntent().getParcelableExtra(KEY_CLIENT_METADATA);

    // If any args are empty, they are invalid and we should finish.
    if (mNestConfig == null || Utils.isAnyEmpty(mNestConfig.getRedirectURL(), mNestConfig.getClientID(),
            mNestConfig.getStateValue())) {
        finishWithResult(RESULT_CANCELED, null);
        return;//from w ww .  ja v a 2s .co  m
    }

    mHttpClient = new OkHttpClient();

    clientWebView.setWebChromeClient(new ProgressChromeClient());
    clientWebView.setWebViewClient(new RedirectClient());

    String url = String.format(NestAPI.CLIENT_CODE_URL, mNestConfig.getClientID(), mNestConfig.getStateValue());
    WebSettings webSettings = clientWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    clientWebView.loadUrl(url);
}

From source file:org.golang.app.WViewActivity.java

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

    //Fixed Portrait orientation
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    /*this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);*/

    setContentView(R.layout.webview);/*from w w w . ja  v  a  2  s .c  om*/
    WebView webView = (WebView) findViewById(R.id.webView1);

    initWebView(webView);
    webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Log.d("JavaGoWV: ", url);

            final Pattern p = Pattern.compile("dcoinKey&password=(.*)$");
            final Matcher m = p.matcher(url);
            if (m.find()) {
                try {
                    Thread thread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                //File root = android.os.Environment.getExternalStorageDirectory();
                                File dir = Environment
                                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                                Log.d("JavaGoWV", "dir " + dir);

                                URL keyUrl = new URL(
                                        "http://127.0.0.1:8089/ajax?controllerName=dcoinKey&first=1"); //you can write here any link
                                //URL keyUrl = new URL("http://yandex.ru/"); //you can write here any link
                                File file = new File(dir, "dcoin-key.png");

                                long startTime = System.currentTimeMillis();
                                Log.d("JavaGoWV", "download begining");
                                Log.d("JavaGoWV", "download keyUrl:" + keyUrl);

                                /* Open a connection to that URL. */
                                URLConnection ucon = keyUrl.openConnection();

                                Log.d("JavaGoWV", "0");
                                /*
                                * Define InputStreams to read from the URLConnection.
                                */
                                InputStream is = ucon.getInputStream();

                                Log.d("JavaGoWV", "01");

                                BufferedInputStream bis = new BufferedInputStream(is);

                                Log.d("JavaGoWV", "1");
                                /*
                                * Read bytes to the Buffer until there is nothing more to read(-1).
                                */
                                ByteArrayBuffer baf = new ByteArrayBuffer(5000);
                                int current = 0;
                                while ((current = bis.read()) != -1) {
                                    baf.append((byte) current);
                                }

                                Log.d("JavaGoWV", "2");
                                /* Convert the Bytes read to a String. */
                                FileOutputStream fos = new FileOutputStream(file);
                                fos.write(baf.toByteArray());
                                fos.flush();
                                fos.close();

                                Log.d("JavaGoWV", "3");
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                                    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                                    Uri contentUri = Uri.fromFile(file);
                                    mediaScanIntent.setData(contentUri);
                                    WViewActivity.this.sendBroadcast(mediaScanIntent);
                                } else {
                                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                                            Uri.parse("file://" + Environment.getExternalStorageDirectory())));
                                }

                                Log.d("JavaGoWV", "4");
                            } catch (Exception e) {
                                Log.e("JavaGoWV error 0", e.toString());
                                e.printStackTrace();
                            }
                        }
                    });
                    thread.start();

                } catch (Exception e) {
                    Log.e("JavaGoWV error", e.toString());
                    e.printStackTrace();
                }
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            Log.e("JavaGoWV", "shouldOverrideUrlLoading " + url);

            if (url.endsWith(".mp4")) {
                Intent in = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(in);
                return true;
            } else {
                return false;
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Log.d("JavaGoWV",
                    "failed: " + failingUrl + ", error code: " + errorCode + " [" + description + "]");
        }
    });

    SystemClock.sleep(1500);
    //if (MyService.DcoinStarted(8089)) {
    webView.loadUrl("http://localhost:8089/");
    //}

}

From source file:com.concentricsky.android.khanacademy.app.ShowProfileActivity.java

/**
 * Get the current user, and fail if there is none.
 */// w  w w .jav  a  2s .c  om
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    destroyed = false;
    this.webViewTimeoutPromptDialog = new AlertDialog.Builder(this)
            .setMessage("The page is taking a long time to respond. Stop loading?")
            .setPositiveButton("Stop", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    if (webView != null) {
                        webView.stopLoading();
                        finish();
                    }
                }
            }).setNegativeButton("Wait", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    stopWebViewLoadTimeout();
                }
            }).setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    startWebViewLoadTimeout();
                }
            }).create();

    getActionBar().setDisplayHomeAsUpEnabled(true);

    setContentView(R.layout.profile);
    setTitle(getString(R.string.profile_title));
    webView = (WebView) findViewById(R.id.web_view);
    webView.setMinimumWidth(800);
    enableJavascript(webView);
    webView.getSettings().setDefaultZoom(ZoomDensity.FAR);
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, String url) {
            Log.d(LOG_TAG, "shouldOverrideUrlLoading: " + url);
            URL parsed = null;
            try {
                parsed = new URL(url);
            } catch (MalformedURLException e) {
                // Let the webview figure that one out.
                return false;
            }

            // Only ka links will load in this webview.
            if (parsed.getHost().equals("www.khanacademy.org")) {

                // Video urls should link into video detail. See below for another video url format.
                if (parsed.getPath().equals("/video")) {
                    String query = parsed.getQuery();
                    if (query != null && query.length() > 0) {
                        String[] items = query.split("&");
                        String videoId = null;
                        for (String item : items) {
                            String[] parts = item.split("=", 2);
                            if (parts.length > 1) {
                                if ("v".equals(parts[0])) {
                                    videoId = parts[1];
                                    break;
                                }
                            }
                        }
                        if (videoId != null) {
                            String[] ids = normalizeVideoAndTopicId(videoId, "");
                            if (ids != null) {
                                launchVideoDetailActivity(ids[0], ids[1]);
                                return true;
                            }
                        }
                    }
                    // There was no ?v= or something weird is going on. Allow the page
                    // load, which should hit KA's nice "no video found" page.
                    showSpinner();
                    startWebViewLoadTimeout();
                    return false;
                }

                if (parsed.getPath().startsWith("/profile")) {
                    // navigation within the profile makes sense here.
                    showSpinner();
                    startWebViewLoadTimeout();
                    return false;
                }

                // Embedded logout option (in upper left menu) can be intercepted and cause the app to be logged out as well.
                if (parsed.getPath().equals("/logout")) {
                    if (dataService != null) {
                        dataService.getAPIAdapter().logout();
                    }
                    finish();
                    return false; // try to let the webview hit logout to get the cookies cleared as we exit
                }

                // There is a new kind of video url now.. thanks guys..
                // http://www.khanacademy.org/video/subtraction-2
                //  redirects to
                // http://www.khanacademy.org/math/arithmetic/addition-subtraction/two_dig_add_sub/v/subtraction-2
                String[] path = parsed.getPath().split("/");
                List<String> parts = Arrays.asList(path);
                if (parts.contains("v")) {
                    String videoId = null;
                    String topicId = null;
                    for (int i = path.length - 1; i >= 0; --i) {
                        if (path[i].equals("v")) {
                            continue;
                        }
                        if (videoId == null) {
                            videoId = path[i];
                        } else if (topicId == null) {
                            topicId = path[i];
                        } else {
                            break;
                        }
                    }

                    if (videoId != null && topicId != null && dataService != null) {
                        // Looks like a video url. Double check that we have the topic and video before launching detail activity.
                        Log.d(LOG_TAG, "video and topic ids found; looks like a video url.");

                        String[] ids = normalizeVideoAndTopicId(videoId, topicId);
                        if (ids != null) {
                            launchVideoDetailActivity(ids[0], ids[1]);
                            return true;
                        }
                    }
                } else if (parsed.getPath().startsWith("/video")) {
                    String videoId = path[path.length - 1];
                    String[] ids = normalizeVideoAndTopicId(videoId, "");
                    if (ids != null) {
                        launchVideoDetailActivity(ids[0], ids[1]);
                        return true;
                    }
                }

                //               showSpinner();
                //               startWebViewLoadTimeout();
                //               return false;
            }

            // All other urls should launch in the browser instead of here, except hash changes if we can distinguish.
            loadInBrowser(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            Log.d(LOG_TAG, "onPageFinished");
            stopWebViewLoadTimeout();
            if (!destroyed) {
                hideSpinner();
            }
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Log.d(LOG_TAG, "onPageStarted");
            stopWebViewLoadTimeout();

            //            view.loadUrl("javascript:document.addEventListener( 'DOMContentLoaded',function() {AndroidApplication.jqueryReady()} );");

            //            handler.postDelayed(new Runnable() {
            //               @Override
            //               public void run() {
            //                  if (!destroyed) {
            //                     hijack();
            //                  }
            //               }
            //            }, 100);
        }
    });
    //      webView.addJavascriptInterface(new Object() {
    //         public void log(String msg) {
    //            Log.d(LOG_TAG, "JSLOG: " + msg);
    //         }
    //         public void jqueryReady() {
    //            Log.d(LOG_TAG, "javascript: jqueryReady");
    //            hijack();
    //         }
    //      }, "AndroidApplication");
    //      
    showSpinner();

    requestDataService(new ObjectCallback<KADataService>() {
        @Override
        public void call(KADataService service) {
            dataService = service;
            api = service.getAPIAdapter();

            String[] credentials = getCurrentLoginCredentials();
            loginUser(credentials[0], credentials[1]);
        }
    });
}

From source file:org.openhab.habdroid.ui.OpenHABWidgetSettingsAdapter.java

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    /* TODO: This definitely needs some huge refactoring
     *///  w  ww .  ja v  a  2  s.c o  m
    final int pos = position;

    RelativeLayout widgetView;
    TextView labelTextView;
    ImageView roomEditView;
    int widgetLayout = 0;
    OpenHABWidget openHABWidget = getItem(position);
    switch (this.getItemViewType(position)) {
    case TYPE_FRAME:
        widgetLayout = R.layout.openhabwidgetlist_frameitem;
        break;
    case TYPE_GROUP:
        widgetLayout = R.layout.openhabwidget_settings_item;
        break;

    case TYPE_IMAGE:
        widgetLayout = R.layout.openhabwidgetlist_imageitem;
        break;

    case TYPE_CHART:
        widgetLayout = R.layout.openhabwidgetlist_chartitem;
        break;
    case TYPE_VIDEO:
        widgetLayout = R.layout.openhabwidgetlist_videoitem;
        break;
    case TYPE_WEB:
        widgetLayout = R.layout.openhabwidgetlist_webitem;
        break;
    default:
        widgetLayout = R.layout.openhabwidget_settings_item;
        break;
    }
    if (convertView == null) {
        widgetView = new RelativeLayout(getContext());
        String inflater = Context.LAYOUT_INFLATER_SERVICE;
        LayoutInflater vi;
        vi = (LayoutInflater) getContext().getSystemService(inflater);
        vi.inflate(widgetLayout, widgetView, true);
    } else {
        widgetView = (RelativeLayout) convertView;
    }
    switch (getItemViewType(position)) {
    case TYPE_FRAME:
        labelTextView = (TextView) widgetView.findViewById(R.id.framelabel);
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        widgetView.setClickable(false);
        if (openHABWidget.getLabel().length() > 0) { // hide empty frames
            widgetView.setVisibility(View.VISIBLE);
            labelTextView.setVisibility(View.VISIBLE);
        } else {
            widgetView.setVisibility(View.GONE);
            labelTextView.setVisibility(View.GONE);
        }
        break;
    case TYPE_IMAGE:
        MySmartImageView imageImage = (MySmartImageView) widgetView.findViewById(R.id.imageimage);
        imageImage.setImageUrl(ensureAbsoluteURL(openHABBaseUrl, openHABWidget.getUrl()), false);
        if (openHABWidget.getRefresh() > 0) {
            imageImage.setRefreshRate(openHABWidget.getRefresh());
            refreshImageList.add(imageImage);
        }
        break;
    case TYPE_CHART:
        MySmartImageView chartImage = (MySmartImageView) widgetView.findViewById(R.id.chartimage);
        OpenHABItem chartItem = openHABWidget.getItem();
        Random random = new Random();
        String chartUrl = "";
        if (chartItem.getType().equals("GroupItem")) {
            chartUrl = openHABBaseUrl + "rrdchart.png?groups=" + chartItem.getName() + "&period="
                    + openHABWidget.getPeriod() + "&random=" + String.valueOf(random.nextInt());
        }
        Log.i("OpenHABWidgetAdapter", "Chart url = " + chartUrl);
        chartImage.setImageUrl(chartUrl, false);
        // TODO: This is quite dirty fix to make charts look full screen width on all displays
        ViewGroup.LayoutParams chartLayoutParams = chartImage.getLayoutParams();
        int screenWidth = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
                .getDefaultDisplay().getWidth();
        chartLayoutParams.height = (int) (screenWidth / 1.88);
        chartImage.setLayoutParams(chartLayoutParams);
        if (openHABWidget.getRefresh() > 0) {
            chartImage.setRefreshRate(openHABWidget.getRefresh());
            refreshImageList.add(chartImage);
        }
        Log.i("OpenHABWidgetAdapter",
                "chart size = " + chartLayoutParams.width + " " + chartLayoutParams.height);
        break;
    case TYPE_VIDEO:
        VideoView videoVideo = (VideoView) widgetView.findViewById(R.id.videovideo);
        Log.i("OpenHABWidgetAdapter", "Opening video at " + openHABWidget.getUrl());
        // TODO: This is quite dirty fix to make video look maximum available size on all screens
        WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        ViewGroup.LayoutParams videoLayoutParams = videoVideo.getLayoutParams();
        videoLayoutParams.height = (int) (wm.getDefaultDisplay().getWidth() / 1.77);
        videoVideo.setLayoutParams(videoLayoutParams);
        // We don't have any event handler to know if the VideoView is on the screen
        // so we manage an array of all videos to stop them when user leaves the page
        if (!videoWidgetList.contains(videoVideo))
            videoWidgetList.add(videoVideo);
        // Start video
        if (!videoVideo.isPlaying()) {
            videoVideo.setVideoURI(Uri.parse(openHABWidget.getUrl()));
            videoVideo.start();
        }
        Log.i("OpenHABWidgetAdapter", "Video height is " + videoVideo.getHeight());
        break;
    case TYPE_WEB:
        WebView webWeb = (WebView) widgetView.findViewById(R.id.webweb);
        if (openHABWidget.getHeight() > 0) {
            ViewGroup.LayoutParams webLayoutParams = webWeb.getLayoutParams();
            webLayoutParams.height = openHABWidget.getHeight() * 80;
            webWeb.setLayoutParams(webLayoutParams);
        }
        webWeb.setWebViewClient(new WebViewClient());
        webWeb.loadUrl(openHABWidget.getUrl());
        break;

    default:
        labelTextView = (TextView) widgetView.findViewById(R.id.itemlabel);
        roomEditView = (ImageView) widgetView.findViewById(R.id.editimg);
        if (null != roomEditView) {
            roomEditView.setVisibility(View.VISIBLE);
            roomEditView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    if (null != listItemListener)
                        listItemListener.onEditClickListener(pos);
                }
            });
        }
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        MySmartImageView sliderImage = (MySmartImageView) widgetView.findViewById(R.id.itemimage);
        sliderImage.setImageUrl(openHABBaseUrl + "images/" + openHABWidget.getIcon() + ".png");
        break;
    }
    LinearLayout dividerLayout = (LinearLayout) widgetView.findViewById(R.id.listdivider);
    if (dividerLayout != null) {
        if (position < this.getCount() - 1) {
            if (this.getItemViewType(position + 1) == TYPE_FRAME) {
                dividerLayout.setVisibility(View.GONE); // hide dividers before frame widgets
            } else {
                dividerLayout.setVisibility(View.VISIBLE); // show dividers for all others
            }
        } else { // last widget in the list, hide divider
            dividerLayout.setVisibility(View.GONE);
        }
    }
    return widgetView;
}

From source file:com.air.mobilebrowser.BrowserActivity.java

/** 
 * Configure a webview to use the activity as
 * its client, and update its settings with 
 * the desired parameters for the activity.
 * @param webView the webview to configure.
 *//*from   w  w w .  j av a  2  s.  c o  m*/
private void configureWebView(WebView webView) {
    webView.clearCache(true);
    webView.setWebViewClient(new SecureWebClient(this));

    WebSettings settings = mWebView.getSettings();
    settings.setBuiltInZoomControls(true);
    settings.setJavaScriptEnabled(true);
    //      settings.setPluginState(PluginState.ON_DEMAND);
    settings.setPluginState(PluginState.ON);
    settings.setAllowFileAccess(true);
    settings.setAllowContentAccess(true);
    settings.setSaveFormData(false);
    settings.setSavePassword(false);
    webView.clearFormData();
    settings.setDomStorageEnabled(true);
    String defaultUserAgent = settings.getUserAgentString();

    StringBuilder sb = new StringBuilder();
    sb.append(defaultUserAgent);
    sb.append(" SmarterSecureBrowser/1.0");
    sb.append(" OS/");
    sb.append(mDeviceStatus.operatingSystem);
    sb.append(" Version/");
    sb.append(mDeviceStatus.operatingSystemVersion);
    sb.append(" Model/");
    sb.append(mDeviceStatus.model);

    settings.setUserAgentString(sb.toString());
}

From source file:com.facebook.react.views.webview.ReactWebViewManager.java

@Override
protected void addEventEmitters(ThemedReactContext reactContext, WebView view) {
    // Do not register default touch emitter and let WebView implementation handle touches
    view.setWebViewClient(new ReactWebViewClient());
}

From source file:com.openatk.rockapp.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    boolean result = false;

    switch (item.getItemId()) {
    case R.id.add:
        addRock();/*from w  ww . j a v  a 2 s.c  o  m*/
        result = true;
        break;

    case R.id.gps:
        Location myLoc = map.getMyLocation();
        if (myLoc == null) {
            Toast.makeText(this, R.string.location_wait, Toast.LENGTH_SHORT).show();
        } else {
            CameraPosition oldPos = map.getCameraPosition();
            CameraPosition newPos = new CameraPosition(new LatLng(myLoc.getLatitude(), myLoc.getLongitude()),
                    map.getMaxZoomLevel(), oldPos.tilt, oldPos.bearing);
            map.animateCamera(CameraUpdateFactory.newCameraPosition(newPos));
        }
        result = true;
        break;

    case R.id.all_rocks:
        // set the new showHide, update the map, and update the action bar
        changeRockTypeShowHide(STATE_ROCKS_BOTH);
        result = true;
        break;

    case R.id.not_picked_rocks:
        // set the new showHide, update the map, and update the action bar
        changeRockTypeShowHide(STATE_ROCKS_NOT_PICKED_UP);
        result = true;
        break;

    case R.id.picked_rocks:
        // set the new showHide, update the map, and update the action bar
        changeRockTypeShowHide(STATE_ROCKS_PICKED_UP);
        result = true;
        break;

    case R.id.list:
        // showRockList();
        result = true;
        break;

    case R.id.rock_delete:
        showConfirmRockDeleteAlert();
        result = true;
        break;

    case R.id.rock_undo_move:
        undoRockMove();
        result = true;
        break;

    case R.id.sync:
        //Tell trello app to sync
        TrelloContentProvider.Sync(this.getApplicationContext().getPackageName());
        result = true;
        break;
    case R.id.menu_help:
        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle("Help");
        WebView wv = new WebView(this);
        wv.loadUrl("file:///android_asset/Help.html");
        wv.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        alert.setView(wv);
        alert.setNegativeButton("Close", null);
        alert.show();
        break;
    case R.id.menu_legal:
        CharSequence licence = "The MIT License (MIT)\n" + "\n" + "Copyright (c) 2013 Purdue University\n"
                + "\n" + "Permission is hereby granted, free of charge, to any person obtaining a copy "
                + "of this software and associated documentation files (the \"Software\"), to deal "
                + "in the Software without restriction, including without limitation the rights "
                + "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell "
                + "copies of the Software, and to permit persons to whom the Software is "
                + "furnished to do so, subject to the following conditions:" + "\n"
                + "The above copyright notice and this permission notice shall be included in "
                + "all copies or substantial portions of the Software.\n" + "\n"
                + "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR "
                + "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, "
                + "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE "
                + "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER "
                + "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, "
                + "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN "
                + "THE SOFTWARE.\n";
        new AlertDialog.Builder(this).setTitle("Legal").setMessage(licence)
                .setIcon(android.R.drawable.ic_dialog_alert).setPositiveButton("Close", null).show();
        break;
    }

    // If we didn't handle, let the super version try
    return result | super.onOptionsItemSelected(item);
}