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:system.info.reader.java

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

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

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    resolutions = Properties.resolution(dm);
    Properties.resolution = resolutions[0] + "*" + resolutions[1];
    int tabHeight = 30, tabWidth = 80;
    if (dm.widthPixels >= 480) {
        tabHeight = 40;/*from   w w  w . java 2s  .c  o  m*/
        tabWidth = 120;
    }

    tabHost = getTabHost();
    LayoutInflater.from(this).inflate(R.layout.main, tabHost.getTabContentView(), true);
    tabHost.addTab(
            tabHost.newTabSpec("tab1").setIndicator(getString(R.string.brief)).setContent(R.id.PropertyList));
    tabHost.addTab(
            tabHost.newTabSpec("tab2").setIndicator(getString(R.string.online)).setContent(R.id.ViewServer));
    tabHost.addTab(
            tabHost.newTabSpec("tab3").setIndicator(getString(R.string.apps)).setContent(R.id.sViewApps));
    tabHost.addTab(
            tabHost.newTabSpec("tab4").setIndicator(getString(R.string.process)).setContent(R.id.sViewProcess));
    tabHost.addTab(tabHost.newTabSpec("tab5").setIndicator("Services").setContent(R.id.sViewCpu));
    tabHost.addTab(tabHost.newTabSpec("tab6").setIndicator("Tasks").setContent(R.id.sViewMem));
    //tabHost.addTab(tabHost.newTabSpec("tab7")
    //        .setIndicator("Vending")
    //        .setContent(R.id.sViewDisk));
    AppsText = (TextView) findViewById(R.id.TextViewApps);
    ProcessText = (TextView) findViewById(R.id.TextViewProcess);
    ServiceText = (TextView) findViewById(R.id.TextViewCpu);
    TaskText = (TextView) findViewById(R.id.TextViewMem);

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(tabWidth, tabHeight);
    for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++)
        tabHost.getTabWidget().getChildAt(i).setLayoutParams(lp);

    properList = (ListView) findViewById(R.id.PropertyList);
    Properties.properListItem = new ArrayList<HashMap<String, Object>>();
    properListItemAdapter = new SimpleAdapter(this, Properties.properListItem, R.layout.property_list,
            new String[] { "ItemTitle", "ItemText" }, new int[] { R.id.ItemTitle, R.id.ItemText });
    properList.setAdapter(properListItemAdapter);
    properList.setOnItemClickListener(mpropertyCL);

    //will support app list later
    //appList = (ListView)findViewById(R.id.AppList);
    //Properties.appListItem = new ArrayList<HashMap<String, Object>>();  
    //SimpleAdapter appListItemAdapter = new SimpleAdapter(this, Properties.appListItem,   
    //             R.layout.app_list,  
    //             new String[] {"ItemTitle", "ItemText"},   
    //             new int[] {R.id.ItemTitle, R.id.ItemText}  
    //         );  
    //appList.setAdapter(appListItemAdapter);

    serverWeb = (WebView) findViewById(R.id.ViewServer);
    WebSettings webSettings = serverWeb.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setUserAgentString("sys.info.trial" + versionCode);
    webSettings.setTextSize(WebSettings.TextSize.SMALLER);
    serverWeb.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return false;//this will not launch browser when redirect.
        }

        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }
    });

    PackageManager pm = getPackageManager();
    try {
        PackageInfo pi = pm.getPackageInfo("sys.info.trial", 0);
        version = "v" + pi.versionName;
        versionCode = pi.versionCode;

        List<PackageInfo> apps = getPackageManager().getInstalledPackages(0);
        nApk = Integer.toString(apps.size());
        apklist = "";
        for (PackageInfo app : apps) {
            apklist += app.packageName + "\t(" + app.versionName + ")\n";
        }
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }

    showDialog(0);
    initPropList();
    //refresh();
    PageTask task = new PageTask();
    task.execute("");
}

From source file:rdx.andro.forexcapplugins.childBrowser.ChildBrowser.java

/**
 * Display a new browser with the specified URL.
 * /*from  ww w . ja v a 2  s .  c o  m*/
 * @param url
 *            The url to load.
 * @param jsonObject
 */
public String showWebPage(final String url, JSONObject options) {
    // Determine if we should hide the location bar.
    if (options != null) {
        showLocationBar = options.optBoolean("showLocationBar", true);
    }

    // Create dialog in new thread
    Runnable runnable = new Runnable() {
        /**
         * Convert our DIP units to Pixels
         * 
         * @return int
         */
        private int dpToPixels(int dipValue) {
            int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dipValue,
                    cordova.getActivity().getResources().getDisplayMetrics());

            return value;
        }

        public void run() {
            // Let's create the main dialog
            dialog = new Dialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
            dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                public void onDismiss(DialogInterface dialog) {
                    try {
                        JSONObject obj = new JSONObject();
                        obj.put("type", CLOSE_EVENT);

                        sendUpdate(obj, false);
                    } catch (JSONException e) {
                        Log.d(LOG_TAG, "Should never happen");
                    }
                }
            });

            // Main container layout
            LinearLayout main = new LinearLayout(cordova.getActivity());
            main.setOrientation(LinearLayout.VERTICAL);

            // Toolbar layout
            RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
            toolbar.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, this.dpToPixels(44)));
            toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
            toolbar.setHorizontalGravity(Gravity.LEFT);
            toolbar.setVerticalGravity(Gravity.TOP);

            // Action Button Container layout
            RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
            actionButtonContainer.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
            actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
            actionButtonContainer.setId(1);

            // Back button
            ImageButton back = new ImageButton(cordova.getActivity());
            RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
            backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            back.setLayoutParams(backLayoutParams);
            back.setContentDescription("Back Button");
            back.setId(2);
            try {
                back.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_left.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });

            // Forward button
            ImageButton forward = new ImageButton(cordova.getActivity());
            RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
            forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
            forward.setLayoutParams(forwardLayoutParams);
            forward.setContentDescription("Forward Button");
            forward.setId(3);
            try {
                forward.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_right.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            forward.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goForward();
                }
            });

            // Edit Text Box
            edittext = new EditText(cordova.getActivity());
            RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
            textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
            textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
            edittext.setLayoutParams(textLayoutParams);
            edittext.setId(4);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
            edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
            edittext.setInputType(InputType.TYPE_NULL); // Will not except
            // input... Makes
            // the text
            // NON-EDITABLE
            edittext.setOnKeyListener(new View.OnKeyListener() {
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    // If the event is a key-down event on the "enter"
                    // button
                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        navigate(edittext.getText().toString());
                        return true;
                    }
                    return false;
                }
            });

            // Close button
            ImageButton close = new ImageButton(cordova.getActivity());
            RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
            closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            close.setLayoutParams(closeLayoutParams);
            forward.setContentDescription("Close Button");
            close.setId(5);
            try {
                close.setImageBitmap(loadDrawable("www/childbrowser/icon_close.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });

            // WebView
            webview = new WebView(cordova.getActivity());
            webview.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
            webview.setWebChromeClient(new WebChromeClient());
            WebViewClient client = new ChildBrowserClient(edittext);
            webview.setWebViewClient(client);
            WebSettings settings = webview.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(true);
            // settings.setPluginState(true);
            settings.setDomStorageEnabled(true);
            webview.loadUrl(url);
            webview.setId(6);
            webview.getSettings().setLoadWithOverviewMode(true);
            webview.getSettings().setUseWideViewPort(true);
            webview.requestFocus();
            webview.requestFocusFromTouch();

            // Add the back and forward buttons to our action button
            // container layout
            actionButtonContainer.addView(back);
            actionButtonContainer.addView(forward);

            // Add the views to our toolbar
            toolbar.addView(actionButtonContainer);
            toolbar.addView(edittext);
            toolbar.addView(close);

            // Don't add the toolbar if its been disabled
            if (getShowLocationBar()) {
                // Add our toolbar to our main view/layout
                main.addView(toolbar);
            }

            // Add our webview to our main view/layout
            main.addView(webview);

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.FILL_PARENT;
            lp.height = WindowManager.LayoutParams.FILL_PARENT;

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
        }

        private Bitmap loadDrawable(String filename) throws java.io.IOException {
            InputStream input = cordova.getActivity().getAssets().open(filename);
            return BitmapFactory.decodeStream(input);
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
    return "";
}

From source file:com.example.administrator.mywebviewdrawsign.SysWebView.java

/**
 * Initialize webview./*from   w  ww .  j  a v a 2  s  . c om*/
 */
@SuppressLint({ "NewApi", "SetJavaScriptEnabled" })
private void setup() {
    this.setInitialScale(0);
    this.setVerticalScrollBarEnabled(true);
    this.setHorizontalScrollBarEnabled(true);
    this.requestFocusFromTouch();
    // Enable JavaScript
    WebSettings settings = this.getSettings();

    settings.setBuiltInZoomControls(false);// ??
    settings.setUseWideViewPort(false);
    settings.setLoadWithOverviewMode(true);
    settings.setJavaScriptEnabled(true);
    settings.setJavaScriptCanOpenWindowsAutomatically(true);
    settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
    settings.setAllowFileAccess(true);
    settings.setAppCacheMaxSize(1024 * 1024 * 32);
    settings.setAppCachePath(mContext.getFilesDir().getPath() + "/cache");
    settings.setAppCacheEnabled(true);
    settings.setCacheMode(WebSettings.LOAD_DEFAULT);
    // Set Cache Mode: LOAD_NO_CACHE is noly for debug
    //settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
    //enablePageCache(settings,5);
    //enableWorkers(settings);

    // Enable database
    settings.setDatabaseEnabled(true);
    String databasePath = mContext.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
    settings.setDatabasePath(databasePath);

    // Enable DOM storage
    settings.setDomStorageEnabled(true);

    // Enable built-in geolocation
    settings.setGeolocationEnabled(true);

    // Improve render performance
    settings.setRenderPriority(WebSettings.RenderPriority.HIGH);

    if (Build.VERSION.SDK_INT >= 21) {
        settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
    }
}

From source file:net.evecom.androidecssp.base.BaseWebActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mContext = this;
    temp = HttpUtil.getPageSize(this);
    setContentView(R.layout.message_post_web);
    // dialog = ProgressDialog.show(BaseWebActivity.this, null,
    // "..");/*from w w  w. j  a  v a  2 s. c o  m*/
    // dialog.setCancelable(true);

    lineProgressBar = (ProgressBar) findViewById(R.id.webview_progress_id);
    imageView = (ImageView) findViewById(R.id.image_view_at_web);
    webView = (WebView) this.findViewById(R.id.wv_oauth_message);
    CookieSyncManager.createInstance(this);
    CookieSyncManager.getInstance().startSync();
    CookieManager.getInstance().removeSessionCookie();

    webView.setWebViewClient(new BaseWebViewClient((BaseWebActivity) instance));
    webView.setWebChromeClient(new BaseChromeClient((BaseWebActivity) instance));

    // 
    webView.setDownloadListener(new MyWebViewDownLoadListener());
    WebSettings webSettings = webView.getSettings();
    webSettings.setSupportZoom(true);
    // WebViewJavaScript
    webSettings.setJavaScriptEnabled(true);
    webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    webSettings.setBuiltInZoomControls(true);// support zoom
    webSettings.setUseWideViewPort(true);
    webSettings.setLoadWithOverviewMode(true);
    /**  */
    // //
    webSettings.setDatabaseEnabled(true);
    String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
    // 
    webSettings.setGeolocationEnabled(true);
    // 
    webSettings.setGeolocationDatabasePath(dir);
    // 
    webSettings.setDomStorageEnabled(true);
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    int mDensity = metrics.densityDpi;
    if (mDensity == 240) {
        webSettings.setDefaultZoom(ZoomDensity.FAR);
    } else if (mDensity == 160) {
        webSettings.setDefaultZoom(ZoomDensity.MEDIUM);
    } else if (mDensity == 120) {
        webSettings.setDefaultZoom(ZoomDensity.CLOSE);
        // }else if(mDensity == DisplayMetrics..DENSITY_XHIGH){
        // webSettings.setDefaultZoom(ZoomDensity.FAR);
    } else if (mDensity == DisplayMetrics.DENSITY_HIGH) {
        webSettings.setDefaultZoom(ZoomDensity.FAR);
    }

    dialogPress = new AlertDialog.Builder(this).setTitle("").setMessage(":0/0")
            .setPositiveButton("", new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).create();

    webView.addJavascriptInterface(new JsInterface(getApplicationContext()), "androidbase");
    String url = HttpUtil.getPCURL() + "jfs/mobile/androidIndex/jqmobileTest";
    // post
    // webView.postUrl(url, postData) postDatabyte[] 
    // EncodingUtils.getBytes("&pwd=888", charset)
    webView.postUrl(url, EncodingUtils.getBytes("", "BASE64"));

}

From source file:com.cloudexplorers.plugins.childBrowser.ChildBrowser.java

/**
 * Display a new browser with the specified URL.
 * //from   www.  ja  v  a  2s. co m
 * @param url
 *          The url to load.
 * @param jsonObject
 */
public String showWebPage(final String url, JSONObject options) {
    // Determine if we should hide the location bar.
    if (options != null) {
        showLocationBar = options.optBoolean("showLocationBar", true);
    }

    // Create dialog in new thread
    Runnable runnable = new Runnable() {
        /**
         * Convert our DIP units to Pixels
         * 
         * @return int
         */
        private int dpToPixels(int dipValue) {
            int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dipValue,
                    cordova.getActivity().getResources().getDisplayMetrics());

            return value;
        }

        public void run() {
            // Let's create the main dialog
            dialog = new Dialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
            dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                public void onDismiss(DialogInterface dialog) {
                    try {
                        JSONObject obj = new JSONObject();
                        obj.put("type", CLOSE_EVENT);

                        sendUpdate(obj, false);
                    } catch (JSONException e) {
                        Log.d(LOG_TAG, "Should never happen");
                    }
                }
            });

            // Main container layout
            LinearLayout main = new LinearLayout(cordova.getActivity());
            main.setOrientation(LinearLayout.VERTICAL);

            // Toolbar layout
            RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
            toolbar.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, this.dpToPixels(44)));
            toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
            toolbar.setHorizontalGravity(Gravity.LEFT);
            toolbar.setVerticalGravity(Gravity.TOP);

            // Action Button Container layout
            RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
            actionButtonContainer.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
            actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
            actionButtonContainer.setId(1);

            // Back button
            ImageButton back = new ImageButton(cordova.getActivity());
            RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
            backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            back.setLayoutParams(backLayoutParams);
            back.setContentDescription("Back Button");
            back.setId(2);
            try {
                back.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_left.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });

            // Forward button
            ImageButton forward = new ImageButton(cordova.getActivity());
            RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
            forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
            forward.setLayoutParams(forwardLayoutParams);
            forward.setContentDescription("Forward Button");
            forward.setId(3);
            try {
                forward.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_right.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            forward.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goForward();
                }
            });

            // Edit Text Box
            edittext = new EditText(cordova.getActivity());
            RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
            textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
            textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
            edittext.setLayoutParams(textLayoutParams);
            edittext.setId(4);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
            edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
            edittext.setInputType(InputType.TYPE_NULL); // Will not except input...
                                                        // Makes the text
                                                        // NON-EDITABLE
            edittext.setOnKeyListener(new View.OnKeyListener() {
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    // If the event is a key-down event on the "enter" button
                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        navigate(edittext.getText().toString());
                        return true;
                    }
                    return false;
                }
            });

            // Close button
            ImageButton close = new ImageButton(cordova.getActivity());
            RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
            closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            close.setLayoutParams(closeLayoutParams);
            forward.setContentDescription("Close Button");
            close.setId(5);
            try {
                close.setImageBitmap(loadDrawable("www/childbrowser/icon_close.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });

            // WebView
            webview = new WebView(cordova.getActivity());
            webview.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
            webview.setWebChromeClient(new WebChromeClient());
            WebViewClient client = new ChildBrowserClient(edittext);
            webview.setWebViewClient(client);
            WebSettings settings = webview.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(true);
            settings.setPluginsEnabled(true);
            settings.setDomStorageEnabled(true);

            webview.loadUrl(url);
            webview.setId(6);
            webview.getSettings().setLoadWithOverviewMode(true);
            webview.getSettings().setUseWideViewPort(true);
            webview.getSettings().setJavaScriptEnabled(true);
            webview.getSettings().setPluginsEnabled(true);

            webview.requestFocus();
            webview.requestFocusFromTouch();

            // Add the back and forward buttons to our action button container
            // layout
            actionButtonContainer.addView(back);
            actionButtonContainer.addView(forward);

            // Add the views to our toolbar
            toolbar.addView(actionButtonContainer);
            toolbar.addView(edittext);
            toolbar.addView(close);

            // Don't add the toolbar if its been disabled
            if (getShowLocationBar()) {
                // Add our toolbar to our main view/layout
                main.addView(toolbar);
            }

            // Add our webview to our main view/layout
            main.addView(webview);

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.FILL_PARENT;
            lp.height = WindowManager.LayoutParams.FILL_PARENT;

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
        }

        private Bitmap loadDrawable(String filename) throws java.io.IOException {
            InputStream input = cordova.getActivity().getAssets().open(filename);
            return BitmapFactory.decodeStream(input);
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
    return "";
}

From source file:de.madvertise.android.sdk.MadvertiseMraidView.java

public MadvertiseMraidView(Context context) {
    super(context);
    setVerticalScrollBarEnabled(false);/*  www  .  j a  v a  2s. c  om*/
    setHorizontalScrollBarEnabled(false);
    setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    setBackgroundColor(Color.TRANSPARENT);
    WebSettings settings = getSettings();
    settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    settings.setJavaScriptEnabled(true);
    //settings.setPluginsEnabled(true);

    // Initialize the default expand properties.
    DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
    mExpandProperties = new ExpandProperties(metrics.widthPixels, metrics.heightPixels);
    MadvertiseUtil.logMessage(null, Log.INFO,
            "Setting default expandProperties : " + mExpandProperties.toJson().toString());

    // This bridge stays available until this view is destroyed, hence no
    // reloading when displaying new ads is necessary.
    addJavascriptInterface(mBridge, "mraid_bridge");

    setWebViewClient(new WebViewClient() {
        private boolean mError = false;

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, final String url) {
            post(new Runnable() {
                @Override
                public void run() {
                    if (mListener != null) {
                        mListener.onAdClicked();
                    }
                    final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url),
                            getContext().getApplicationContext(), MadvertiseActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    getContext().startActivity(intent);
                }
            });
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (!url.endsWith("mraid.js") && !mError) {
                MadvertiseUtil.logMessage(null, Log.DEBUG, "Setting mraid to default");
                checkReady();

                // Close button in default size for interstitial ads
                if (mPlacementType == MadvertiseUtil.PLACEMENT_TYPE_INTERSTITIAL) {
                    mCloseButton = addCloseButtonToViewGroup(((ViewGroup) getParent()));
                    mCloseButton.setImageResource(android.R.drawable.ic_menu_close_clear_cancel);
                }
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            mError = true;
        }
    });

    // Comment this in to enable video tag-capability.
    this.setWebChromeClient(new WebChromeClient() {

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            MadvertiseUtil.logMessage(null, Log.INFO, "showing VideoView");
            super.onShowCustomView(view, callback);
            if (view instanceof FrameLayout) {
                FrameLayout frame = (FrameLayout) view;
                if (frame.getFocusedChild() instanceof VideoView) {
                    mVideo = (VideoView) ((FrameLayout) view).getFocusedChild();
                    frame.removeView(mVideo);
                    ((ViewGroup) getParent()).addView(mVideo);

                    // Will also be called onError
                    mVideo.setOnCompletionListener(new OnCompletionListener() {

                        @Override
                        public void onCompletion(MediaPlayer player) {
                            player.stop();
                        }
                    });

                    mVideo.setOnErrorListener(new OnErrorListener() {

                        @Override
                        public boolean onError(MediaPlayer mp, int what, int extra) {
                            MadvertiseUtil.logMessage(null, Log.WARN, "Error while playing video");

                            if (mListener != null) {
                                mListener.onError(new IOException("Error while playing video"));
                            }

                            // We return false in order to call
                            // onCompletion()
                            return false;
                        }
                    });

                    mVideo.start();
                }
            }
        }

        @Override
        public void onHideCustomView() {
            if (mVideo != null) {
                ((ViewGroup) getParent()).removeView(mVideo);
                if (mVideo.isPlaying()) {
                    mVideo.stopPlayback();
                }
            }
        }
    });
}

From source file:com.bluekai.sdk.BlueKai.java

private void addBlueKaiWebView(Context context) {
    try {/*from www.  j a  v  a2 s  . co  m*/
        blueKaiView = new BlueKaiWebView(context, this);
        blueKaiView.setWebClient();
        WebSettings webSettings = blueKaiView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        int height = 1, width = 1;
        if (devMode) {
            height = width = RelativeLayout.LayoutParams.MATCH_PARENT;
        }
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, height);
        params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
        params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
        params.setMargins(10, 10, 10, 10);
        blueKaiView.setBackgroundColor(Color.LTGRAY);
        if (activity != null) {
            activity.addContentView(blueKaiView, params);
        } else {
            Logger.warn(TAG, "Activity is null. Cannot add webview");
        }
    } catch (Exception ex) {
        Logger.error(TAG, "Error while adding BlueKai webview", ex);
    }
}

From source file:com.nbplus.hybrid.BasicWebViewClient.java

/**
 * ??./*www .  j av a 2 s.  c o m*/
 * @param activity : context
 * @param view : ?? 
 */
public BasicWebViewClient(Activity activity, WebView view, String alertTitleString, String confirmTitleString) {
    mWebView = view;
    mContext = activity;

    // This will handle downloading. It requires Gingerbread, though
    mDownloadManager = (DownloadManager) mContext.getSystemService(mContext.DOWNLOAD_SERVICE);
    mWebChromeClient = new BroadcastWebChromeClient();

    // Enable remote debugging via chrome://inspect
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        mWebView.setWebContentsDebuggingEnabled(true);
    }
    mWebView.setWebChromeClient(mWebChromeClient);

    WebSettings webSettings = mWebView.getSettings();
    webSettings.setGeolocationEnabled(true);
    webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setDatabaseEnabled(true);
    // Use WideViewport and Zoom out if there is no viewport defined
    webSettings.setUseWideViewPort(true);
    webSettings.setLoadWithOverviewMode(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        webSettings.setMediaPlaybackRequiresUserGesture(false);
    }

    // Enable pinch to zoom without the zoom buttons
    webSettings.setBuiltInZoomControls(true);
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
        // Hide the zoom controls for HONEYCOMB+
        webSettings.setDisplayZoomControls(false);
    }

    webSettings.setAppCacheEnabled(true);
    mWebView.clearCache(true);
    webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        // Sets whether the WebView should allow third party cookies to be set.
        // Allowing third party cookies is a per WebView policy and can be set differently on different WebView instances.

        // Apps that target KITKAT or below default to allowing third party cookies.
        // Apps targeting LOLLIPOP or later default to disallowing third party cookies.
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.setAcceptThirdPartyCookies(mWebView, true);
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        mWebView.getSettings().setTextZoom(100);
    }

    if (StringUtils.isEmptyString(alertTitleString)) {
        mAlertTitleString = activity.getString(R.string.default_webview_alert_title);
    } else {
        mAlertTitleString = alertTitleString;
    }

    if (StringUtils.isEmptyString(confirmTitleString)) {
        mConfirmTitleString = activity.getString(R.string.default_webview_confirm_title);
    } else {
        mConfirmTitleString = confirmTitleString;
    }

    mWebView.setDownloadListener(new DownloadListener() {
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                long contentLength) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(url));
            mContext.startActivity(intent);

        }
    });

    Log.d(TAG, ">> user agent = " + mWebView.getSettings().getUserAgentString());
}

From source file:com.lemon.lime.MainActivity.java

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

    getBatteryPercentage();//from  w  w  w.j ava  2  s.  c  o  m
    setContentView(R.layout.activity_main);
    getSupportActionBar().setDisplayShowCustomEnabled(true);
    getSupportActionBar().setDisplayShowTitleEnabled(false);
    mWebView = (ObservableWebView) findViewById(R.id.activity_main_webview);
    mWebView.setScrollViewCallbacks(this);
    LayoutInflater inflator = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View v = inflator.inflate(R.layout.bar, null);
    getSupportActionBar().setCustomView(v);

    WebIconDatabase.getInstance().open(getDir("icons", MODE_PRIVATE).getPath());

    swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipeToRefresh);
    swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mWebView.reload();
        }
    });
    swipeLayout.setColorSchemeResources(R.color.lili, R.color.colorPrimary, R.color.red);

    window = getWindow();
    favicon = (ImageView) findViewById(R.id.favicon);
    editurl = (EditText) findViewById(R.id.editurl);
    mWebView.setDownloadListener(new DownloadListener() {
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                long contentLength) {

            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }

    });

    favicon.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (lili == 5) {
                lilimode();
                lili = 0;
                lilimode = true;
            } else {
                lili = lili + 1;
            }
        }
    });

    editurl.setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                if (event.getAction() == KeyEvent.ACTION_UP) {
                    if (editurl.getText().toString().contains("file:///")) {
                        filemgr();
                    } else if (editurl.getText().toString().contains("gaymode")) {
                        gaymode();
                    } else if (editurl.getText().toString().contains("exitapp")) {
                        finish();
                    } else if (editurl.getText().toString().contains("light")) {
                        flash();
                    }

                    if (isconnected()) {
                        if (editurl.getText().toString().contains("http://")
                                || editurl.getText().toString().contains("https://")) {
                            mWebView.loadUrl(editurl.getText().toString());

                        } else if (editurl.getText().toString().contains(".com")
                                || editurl.getText().toString().contains(".net")
                                || editurl.getText().toString().contains(".org")
                                || editurl.getText().toString().contains(".gov")
                                || editurl.getText().toString().contains(".hu")
                                || editurl.getText().toString().contains(".sk")
                                || editurl.getText().toString().contains(".co.uk")
                                || editurl.getText().toString().contains(".co.in")
                                || editurl.getText().toString().contains(".cn")
                                || editurl.getText().toString().contains(".it")
                                || editurl.getText().toString().contains(".de")
                                || editurl.getText().toString().contains(".aus")
                                || editurl.getText().toString().contains(".hr")
                                || editurl.getText().toString().contains(".cz")
                                || editurl.getText().toString().contains(".xyz")
                                || editurl.getText().toString().contains(".pl")
                                || editurl.getText().toString().contains(".io")) {
                            mWebView.loadUrl("http://" + editurl.getText().toString());

                            InputMethodManager imm = (InputMethodManager) getSystemService(
                                    Context.INPUT_METHOD_SERVICE);
                            imm.hideSoftInputFromWindow(editurl.getWindowToken(), 0);

                        } else {
                            mWebView.loadUrl("https://www.google.com/search?q=" + editurl.getText().toString());

                            InputMethodManager imm = (InputMethodManager) getSystemService(
                                    Context.INPUT_METHOD_SERVICE);
                            imm.hideSoftInputFromWindow(editurl.getWindowToken(), 0);
                        }
                    }
                    return true;
                }
                return false;
            }

            return true;
        }
    });
    // Enable Javascript
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setBuiltInZoomControls(true);
    webSettings.setDisplayZoomControls(false);
    webSettings.setSupportMultipleWindows(true);

    if (isconnected()) {
        mWebView.loadUrl("http://google.com");
    } else {

        final View coordinatorLayoutView = findViewById(R.id.snackbarPosition);
        mWebView.loadUrl("file:///android_asset/nonet.html");
        Snackbar snackbar = Snackbar.make(coordinatorLayoutView, R.string.offline, Snackbar.LENGTH_LONG);
        snackbar.show();

    }

    mWebView.setWebChromeClient(new WebChromeClient() {

        @Override
        public void onReceivedIcon(WebView mWebView, Bitmap icon) {
            super.onReceivedIcon(mWebView, icon);
            favicon.setImageBitmap(icon);
        }

        public void onProgressChanged(WebView view, int progress) {
            activity.setProgress(progress * 100);
            int a = progress;
            if (lilimode) {
                editurl.setText("Liling: " + Integer.toString(a) + "?");
            } else
                editurl.setText("Liming: " + Integer.toString(a) + "%");
            if (progress == 100) {

                editurl.setHint(view.getTitle());
                activity.setTitle(view.getTitle());
                editurl.setText(view.getUrl());

                fav();

                //battery
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    if (level <= 20) {
                        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                        window.setNavigationBarColor(Color.RED);
                        window.setStatusBarColor(Color.RED);
                        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.RED));
                    }
                }
            }
        }
    });

    mWebView.setWebViewClient(new WebViewClient() {
        public void onPageFinished(WebView mWebView, String url) {
            swipeLayout.setRefreshing(false);
        }
    });

}

From source file:com.chatwingsdk.activities.CommunicationActivity.java

@SuppressLint("SetJavaScriptEnabled")
@Override// w  w w .  j ava  2 s  . c  o m
public void ensureWebViewAndSubscribeToChannels() {
    if (mCurrentCommunicationMode == null)
        return;
    // Check whether the web view is available or not.
    // If not, init it and load faye client. When loading finished,
    // this method will be recursively called. At that point,
    // the actual subscribe code will be executed.
    if (mWebView == null) {
        mNotSubscribeToChannels = true;
        mWebView = new WebView(this);

        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        mWebView.addJavascriptInterface(mFayeJsInterface, ChatWingJSInterface.CHATWING_JS_NAME);

        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {

                LogUtils.v(consoleMessage.message() + " -- level " + consoleMessage.messageLevel()
                        + " -- From line " + consoleMessage.lineNumber() + " of " + consoleMessage.sourceId());

                //This workaround tries to fix issue webview is not subscribe successfully
                //when the screen is off, we cant listen for otto event since it's dead before that
                //this likely happens on development or very rare case in production
                if (consoleMessage.messageLevel().equals(ConsoleMessage.MessageLevel.ERROR)) {
                    mWebView = null;
                    mNotSubscribeToChannels = true;
                }
                return true;
            }
        });

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);

                if (url.equals(Constants.FAYE_CLIENT_URL)) {
                    // Recursively call this method,
                    // to execute subscribe code.
                    ensureWebViewAndSubscribeToChannels();
                }
            }
        });

        mWebView.loadUrl(Constants.FAYE_CLIENT_URL);
        return;
    }
    if (mNotSubscribeToChannels) {
        mNotSubscribeToChannels = false;
        mCurrentCommunicationMode.subscribeToChannels(mWebView);
    }
}