Example usage for android.webkit WebView WebView

List of usage examples for android.webkit WebView WebView

Introduction

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

Prototype

public WebView(Context context) 

Source Link

Document

Constructs a new WebView with an Activity Context object.

Usage

From source file:org.odk.collect.android.widgets.ImageWebViewWidget.java

public ImageWebViewWidget(Context context, FormEntryPrompt prompt) {
    super(context, prompt);

    mInstanceFolder = Collect.getInstance().getFormController().getInstancePath().getParent();

    TableLayout.LayoutParams params = new TableLayout.LayoutParams();
    params.setMargins(7, 5, 7, 5);/* w  w w .j  a va2 s  . c  o m*/

    mErrorTextView = new TextView(context);
    mErrorTextView.setId(QuestionWidget.newUniqueId());
    mErrorTextView.setText("Selected file is not a valid image");

    // setup capture button
    mCaptureButton = new Button(getContext());
    mCaptureButton.setId(QuestionWidget.newUniqueId());
    mCaptureButton.setText(getContext().getString(R.string.capture_image));
    mCaptureButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
    mCaptureButton.setPadding(20, 20, 20, 20);
    mCaptureButton.setEnabled(!prompt.isReadOnly());
    mCaptureButton.setLayoutParams(params);

    // launch capture intent on click
    mCaptureButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Collect.getInstance().getActivityLogger().logInstanceAction(this, "captureButton", "click",
                    mPrompt.getIndex());
            mErrorTextView.setVisibility(View.GONE);
            Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            // We give the camera an absolute filename/path where to put the
            // picture because of bug:
            // http://code.google.com/p/android/issues/detail?id=1480
            // The bug appears to be fixed in Android 2.0+, but as of feb 2,
            // 2010, G1 phones only run 1.6. Without specifying the path the
            // images returned by the camera in 1.6 (and earlier) are ~1/4
            // the size. boo.

            // if this gets modified, the onActivityResult in
            // FormEntyActivity will also need to be updated.
            Uri tempPath = FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".provider",
                    new File(Collect.TMPFILE_PATH));
            i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, tempPath);
            try {
                Collect.getInstance().getFormController().setIndexWaitingForData(mPrompt.getIndex());
                ((Activity) getContext()).startActivityForResult(i, FormEntryActivity.IMAGE_CAPTURE);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(getContext(),
                        getContext().getString(R.string.activity_not_found, "image capture"),
                        Toast.LENGTH_SHORT).show();
                Collect.getInstance().getFormController().setIndexWaitingForData(null);
            }

        }
    });

    // setup chooser button
    mChooseButton = new Button(getContext());
    mChooseButton.setId(QuestionWidget.newUniqueId());
    mChooseButton.setText(getContext().getString(R.string.choose_image));
    mChooseButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mAnswerFontsize);
    mChooseButton.setPadding(20, 20, 20, 20);
    mChooseButton.setEnabled(!prompt.isReadOnly());
    mChooseButton.setLayoutParams(params);

    // launch capture intent on click
    mChooseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Collect.getInstance().getActivityLogger().logInstanceAction(this, "chooseButton", "click",
                    mPrompt.getIndex());
            mErrorTextView.setVisibility(View.GONE);
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.setType("image/*");

            try {
                Collect.getInstance().getFormController().setIndexWaitingForData(mPrompt.getIndex());
                ((Activity) getContext()).startActivityForResult(i, FormEntryActivity.IMAGE_CHOOSER);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(getContext(),
                        getContext().getString(R.string.activity_not_found, "choose image"), Toast.LENGTH_SHORT)
                        .show();
                Collect.getInstance().getFormController().setIndexWaitingForData(null);
            }

        }
    });

    // finish complex layout
    LinearLayout answerLayout = new LinearLayout(getContext());
    answerLayout.setOrientation(LinearLayout.VERTICAL);
    answerLayout.addView(mCaptureButton);
    answerLayout.addView(mChooseButton);
    answerLayout.addView(mErrorTextView);

    // and hide the capture and choose button if read-only
    if (prompt.isReadOnly()) {
        mCaptureButton.setVisibility(View.GONE);
        mChooseButton.setVisibility(View.GONE);
    }
    mErrorTextView.setVisibility(View.GONE);

    // retrieve answer from data model and update ui
    mBinaryName = prompt.getAnswerText();

    // Only add the imageView if the user has taken a picture
    if (mBinaryName != null) {
        mImageDisplay = new WebView(getContext());
        mImageDisplay.setId(QuestionWidget.newUniqueId());
        mImageDisplay.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mImageDisplay.getSettings().setBuiltInZoomControls(true);
        mImageDisplay.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
        mImageDisplay.setVisibility(View.VISIBLE);
        mImageDisplay.setLayoutParams(params);

        // HTML is used to display the image.
        String html = "<body>" + constructImageElement() + "</body>";

        mImageDisplay.loadDataWithBaseURL("file:///" + mInstanceFolder + File.separator, html, "text/html",
                "utf-8", "");
        answerLayout.addView(mImageDisplay);
    }
    addAnswerView(answerLayout);
}

From source file:de.mkrtchyan.recoverytools.SettingsFragment.java

public static void showChangelog(Context AppContext) {
    AlertDialog.Builder dialog = new AlertDialog.Builder(AppContext);
    dialog.setTitle(R.string.changelog);
    WebView changes = new WebView(AppContext);
    changes.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
    changes.setWebViewClient(new WebViewClient());
    changes.loadUrl(Constants.CHANGELOG_URL);
    changes.clearCache(true);/*from w  w w .  j a  v a 2s  .c  om*/
    dialog.setView(changes);
    dialog.show();
}

From source file:de.t_animal.journeyapp.InformationFragment.java

private void showHTMLPopup(View v) {
    String title;//from  ww  w  .  j a v a 2 s  .  c  o m
    String url;

    if (v.getId() == R.id.info_acknowledgement) {
        title = "Acknowledgements";
        url = "file:///android_asset/acknowledgements.html";
    } else {
        title = "License";
        url = "file:///android_asset/license.html";
    }

    WebView wv = new WebView(getActivity());
    wv.loadUrl(url);

    new AlertDialog.Builder(getActivity()).setTitle(title).setView(wv)
            .setNegativeButton("Close", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                }
            }).show();

}

From source file:com.awadev.itslearningautologin.MainActivity.java

private void initUI() {
    // Navigation drawer
    mTitle = mDrawerTitle = getTitle();//from www  . ja v a2  s .co  m
    String[] mPlanetTitles = getResources().getStringArray(R.array.planets_array);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    // set a custom shadow that overlays the main content when the drawer opens
    //mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    // set up the drawer's list view with items and click listener
    mDrawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mPlanetTitles));
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

    // enable ActionBar app icon to behave as action to toggle nav drawer
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the sliding drawer and the action bar app icon
    mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
            mDrawerLayout, /* DrawerLayout object */
            R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
            R.string.drawer_open, /* "open drawer" description for accessibility */
            R.string.drawer_close /* "close drawer" description for accessibility */
    ) {
        public void onDrawerClosed(View view) {
            getSupportActionBar().setTitle(mTitle);
            supportInvalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }

        public void onDrawerOpened(View drawerView) {
            getSupportActionBar().setTitle(mDrawerTitle);
            supportInvalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);
    // End navigation drawer

    webViewPlaceholder = ((RelativeLayout) findViewById(R.id.webViewPlaceholder));

    if (mWebView == null) {
        // Set cookies
        mWebView = new WebView(this);
        mWebView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));

        CookieSyncManager.createInstance(this);
        WebComponent.copyCookies(CookieManager.getInstance());

        // Make the WebView behave like we want
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setSupportMultipleWindows(true);
        mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        mWebView.getSettings().setUserAgentString("itsLearning login - Android");

        mWebView.setWebViewClient(new CustomWebClient());

        // Load!
        String url = ((MainApplication) getApplication()).getLoadUrl();
        if (url != null) {
            mWebView.loadUrl(url);
            ((MainApplication) getApplication()).setLoadUrl(null);
        } else
            mWebView.loadUrl(((MainApplication) getApplication()).baseURL + "/DashboardMenu.aspx");
    }
    // Attach the WebView to its placeholder
    webViewPlaceholder.addView(mWebView);
}

From source file:com.nextgis.mobile.fragment.AttributesFragment.java

private void setAttributes() {
    if (mAttributes == null)
        return;//w w  w . j  av  a2 s . c  om

    mAttributes.removeAllViews();

    int[] attrs = new int[] { android.R.attr.textColorPrimary };
    TypedArray ta = getContext().obtainStyledAttributes(attrs);
    String textColor = Integer.toHexString(ta.getColor(0, Color.BLACK)).substring(2);
    ta.recycle();

    final WebView webView = new WebView(getContext());
    webView.setVerticalScrollBarEnabled(false);
    String data = "<!DOCTYPE html><html><head><meta charset='utf-8'><style>body{word-wrap:break-word;color:#"
            + textColor
            + ";font-family:Roboto Light,sans-serif;font-weight:300;line-height:1.15em}.flat-table{table-layout:fixed;margin-bottom:20px;width:100%;border-collapse:collapse;border:none;box-shadow:inset 1px -1px #ccc,inset -1px 1px #ccc}.flat-table td{box-shadow:inset -1px -1px #ccc,inset -1px -1px #ccc;padding:.5em}.flat-table tr{-webkit-transition:background .3s,box-shadow .3s;-moz-transition:background .3s,box-shadow .3s;transition:background .3s,box-shadow .3s}</style></head><body><table class='flat-table'><tbody>";

    FragmentActivity activity = getActivity();
    if (null == activity)
        return;

    ((MainActivity) activity).setSubtitle(String.format(getString(R.string.features_count_attributes),
            mItemPosition + 1, mFeatureIDs.size()));
    checkNearbyItems();

    try {
        data = parseAttributes(data);
    } catch (RuntimeException e) {
        e.printStackTrace();
    }

    data += "</tbody></table></body></html>";
    webView.loadDataWithBaseURL(null, data, "text/html", "UTF-8", null);
    mAttributes.addView(webView);
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            webView.setBackgroundColor(Color.TRANSPARENT);
        }

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;
        }
    });

    IGISApplication app = (GISApplication) getActivity().getApplication();
    final Map<String, Integer> mAttaches = new HashMap<>();
    PhotoGallery.getAttaches(app, mLayer, mItemId, mAttaches, false);

    if (mAttaches.size() > 0) {
        final PhotoPicker gallery = new PhotoPicker(getActivity(), true);
        int px = ControlHelper.dpToPx(16, getResources());
        gallery.setDefaultPreview(true);
        gallery.setPadding(px, 0, px, 0);
        gallery.post(new Runnable() {
            @Override
            public void run() {
                gallery.restoreImages(new ArrayList<>(mAttaches.keySet()));
            }
        });

        mAttributes.addView(gallery);
    }
}

From source file:com.gmail.boiledorange73.ut.map.MapActivityBase.java

protected void initialize() {
    // appends views
    RelativeLayout layoutRoot = new RelativeLayout(this);
    this.addContentView(layoutRoot,
            new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
    this.mWebView = new WebView(this);
    this.mWebView.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);
    this.mWebView.setLayoutParams(
            new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
    this.applyUserAgent(this.mWebView);
    layoutRoot.addView(this.mWebView);
    this.mWebView.getSettings().setJavaScriptEnabled(true);
    // starts the map application
    this.restart();
}

From source file:nya.miku.wishmaster.http.cloudflare.CloudflareChecker.java

private Cookie checkAntiDDOS(final CloudflareException exception, final HttpHost proxy, CancellableTask task,
        final Activity activity) {
    synchronized (lock) {
        if (processing)
            return null;
        processing = true;/*  ww  w  . ja v  a 2  s.  c  o m*/
    }
    processing2 = true;
    currentCookie = null;

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        CookieSyncManager.createInstance(activity);
        CookieManager.getInstance().removeAllCookie();
    } else {
        CompatibilityImpl.clearCookies(CookieManager.getInstance());
    }

    final ViewGroup layout = (ViewGroup) activity.getWindow().getDecorView().getRootView();
    final WebViewClient client = new WebViewClient() {
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }

        @Override
        public void onPageFinished(WebView webView, String url) {
            super.onPageFinished(webView, url);
            Logger.d(TAG, "Got Page: " + url);
            String value = null;
            try {
                String[] cookies = CookieManager.getInstance().getCookie(url).split("[;]");
                for (String cookie : cookies) {
                    if ((cookie != null) && (!cookie.trim().equals(""))
                            && (cookie.startsWith(" " + exception.getRequiredCookieName() + "="))) {
                        value = cookie.substring(exception.getRequiredCookieName().length() + 2);
                    }
                }
            } catch (NullPointerException e) {
                Logger.e(TAG, e);
            }
            if (value != null) {
                BasicClientCookieHC4 cf_cookie = new BasicClientCookieHC4(exception.getRequiredCookieName(),
                        value);
                cf_cookie.setDomain("." + Uri.parse(url).getHost());
                cf_cookie.setPath("/");
                currentCookie = cf_cookie;
                Logger.d(TAG, "Cookie found: " + value);
                processing2 = false;
            } else {
                Logger.d(TAG, "Cookie is not found");
            }
        }
    };

    activity.runOnUiThread(new Runnable() {
        @SuppressLint("SetJavaScriptEnabled")
        @Override
        public void run() {
            webView = new WebView(activity);
            webView.setVisibility(View.GONE);
            layout.addView(webView);
            webView.setWebViewClient(client);
            webView.getSettings().setUserAgentString(HttpConstants.USER_AGENT_STRING);
            webView.getSettings().setJavaScriptEnabled(true);
            webViewContext = webView.getContext();
            if (proxy != null)
                WebViewProxy.setProxy(webViewContext, proxy.getHostName(), proxy.getPort());
            webView.loadUrl(exception.getCheckUrl());
        }
    });

    long startTime = System.currentTimeMillis();
    while (processing2) {
        long time = System.currentTimeMillis() - startTime;
        if ((task != null && task.isCancelled()) || time > TIMEOUT) {
            processing2 = false;
        }
    }

    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            try {
                layout.removeView(webView);
                webView.stopLoading();
                webView.clearCache(true);
                webView.destroy();
                webView = null;
            } finally {
                if (proxy != null)
                    WebViewProxy.setProxy(webViewContext, null, 0);
                processing = false;
            }
        }
    });

    return currentCookie;
}

From source file:mobisocial.musubi.service.WebRenderService.java

@Override
public void onCreate() {
    super.onCreate();
    mWebView = new WebView(this);
    //set the size before we start
    measureAndLayout();/*from   w  w w . ja v  a  2 s  .  com*/
    mWebViewClient = new RenderWebViewClient();
    mWebView.setWebViewClient(mWebViewClient);
}

From source file:org.tomahawk.libtomahawk.resolver.ScriptResolver.java

/**
 * Initialize the WebView. Loads the .js script from the given path and sets the appropriate
 * base URL./* w ww  . j av a2s.  co m*/
 *
 * @return the initialized WebView
 */
private synchronized WebView getWebView() {
    if (mWebView == null) {
        mWebView = new WebView(TomahawkApp.getContext());
        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setDatabasePath(TomahawkApp.getContext().getDir("databases", Context.MODE_PRIVATE).getPath());
        settings.setDomStorageEnabled(true);
        mWebView.setWebChromeClient(new TomahawkWebChromeClient());
        mWebView.setWebViewClient(new ScriptWebViewClient(ScriptResolver.this));
        final ScriptInterface scriptInterface = new ScriptInterface(ScriptResolver.this);
        mWebView.addJavascriptInterface(scriptInterface, SCRIPT_INTERFACE_NAME);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        }

        final String baseurl = "file:///android_asset/test.html";
        String data = "<!DOCTYPE html>" + "<html><body>"
                + "<script src=\"file:///android_asset/js/cryptojs-core.js"
                + "\" type=\"text/javascript\"></script>";
        for (String scriptPath : mMetaData.manifest.scripts) {
            data += "<script src=\"file:///android_asset/" + mPath + "/" + scriptPath
                    + "\" type=\"text/javascript\"></script>";
        }
        try {
            String[] cryptoJsScripts = TomahawkApp.getContext().getAssets().list("js/cryptojs");
            for (String scriptPath : cryptoJsScripts) {
                data += "<script src=\"file:///android_asset/js/cryptojs/" + scriptPath
                        + "\" type=\"text/javascript\"></script>";
            }
        } catch (IOException e) {
            Log.e(TAG, "ScriptResolver: " + e.getClass() + ": " + e.getLocalizedMessage());
        }
        data += "<script src=\"file:///android_asset/js/tomahawk_android_pre.js"
                + "\" type=\"text/javascript\"></script>" + "<script src=\"file:///android_asset/js/tomahawk.js"
                + "\" type=\"text/javascript\"></script>"
                + "<script src=\"file:///android_asset/js/tomahawk_android_post.js"
                + "\" type=\"text/javascript\"></script>" + "<script src=\"file:///android_asset/" + mPath + "/"
                + mMetaData.manifest.main + "\" type=\"text/javascript\"></script>" + "</body></html>";
        final String finalData = data;
        mWebView.loadDataWithBaseURL(baseurl, finalData, "text/html", null, null);
    }
    return mWebView;
}

From source file:nirwan.cordova.plugin.printer.Printer.java

private void loadContentAsBitmapIntoPrintController(String content, final Intent intent) {
    Activity ctx = cordova.getActivity();
    final WebView page = new WebView(ctx);
    final Printer self = this;

    page.setVisibility(View.INVISIBLE);
    page.getSettings().setJavaScriptEnabled(false);

    page.setWebViewClient(new WebViewClient() {
        @Override// w  ww  .  j av  a2  s  .co  m
        public void onPageFinished(final WebView page, String url) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    Bitmap screenshot = self.takeScreenshot(page);
                    File tmpFile = self.saveScreenshotToTmpFile(screenshot);
                    ViewGroup vg = (ViewGroup) (page.getParent());

                    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(tmpFile));

                    vg.removeView(page);
                }
            }, 1000);
        }
    });

    //Set base URI to the assets/www folder
    String baseURL = webView.getUrl();
    baseURL = baseURL.substring(0, baseURL.lastIndexOf('/') + 1);

    ctx.addContentView(page, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    page.loadDataWithBaseURL(baseURL, content, "text/html", "UTF-8", null);
}