Example usage for android.webkit CookieManager getInstance

List of usage examples for android.webkit CookieManager getInstance

Introduction

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

Prototype

public static CookieManager getInstance() 

Source Link

Document

Gets the singleton CookieManager instance.

Usage

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

@SuppressLint("NewApi")
public void setThirdPartyCookiesEnabled(final boolean enabled) {
    if (Build.VERSION.SDK_INT >= 21) {
        CookieManager.getInstance().setAcceptThirdPartyCookies(this, enabled);
    }/*from   ww w.  java 2  s .com*/
}

From source file:com.pindroid.fragment.ViewBookmarkFragment.java

private void showInWebView(String url) {
    String readingBackground = SettingsHelper.getReadingBackground(getActivity());
    String readingFont = SettingsHelper.getReadingFont(getActivity());
    String readingFontSize = SettingsHelper.getReadingFontSize(getActivity());
    String readingMargins = SettingsHelper.getReadingMargins(getActivity());

    mWebContent.loadUrl("about:blank");
    mWebContent.clearCache(true);/*w w w  .j av a  2 s . com*/

    CookieManager cookieManager = CookieManager.getInstance();
    CookieSyncManager.createInstance(getActivity());

    cookieManager.setAcceptCookie(true);
    cookieManager.setCookie("http://www.instapaper.com",
            "iptcolor=" + readingBackground + "; expires=Sat, 25-Mar-2023 00:00:00 GMT;path=/;");
    cookieManager.setCookie("http://www.instapaper.com",
            "iptfont=" + readingFont + "; expires=Sat, 25-Mar-2023 00:00:00 GMT;path=/;");
    cookieManager.setCookie("http://www.instapaper.com",
            "iptsize=" + readingFontSize + "; expires=Sat, 25-Mar-2023 00:00:00 GMT;path=/;");
    cookieManager.setCookie("http://www.instapaper.com",
            "iptwidth=" + readingMargins + "; expires=Sat, 25-Mar-2023 00:00:00 GMT;path=/;");

    CookieSyncManager.getInstance().sync();

    mWebContent.setWebViewClient(new WebViewClient() {
    });

    mWebContent.loadUrl(url);
}

From source file:org.mozilla.focus.fragment.BrowserFragment.java

/**
 * Use Android's Download Manager to queue this download.
 *///from  ww  w  .j ava 2s . c o m
private void queueDownload(Download download) {
    if (download == null) {
        return;
    }

    final Context context = getContext();
    if (context == null) {
        return;
    }

    final String cookie = CookieManager.getInstance().getCookie(download.getUrl());
    final String fileName = URLUtil.guessFileName(download.getUrl(), download.getContentDisposition(),
            download.getMimeType());

    final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(download.getUrl()))
            .addRequestHeader("User-Agent", download.getUserAgent()).addRequestHeader("Cookie", cookie)
            .addRequestHeader("Referer", getUrl())
            .setDestinationInExternalPublicDir(download.getDestinationDirectory(), fileName)
            .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
            .setMimeType(download.getMimeType());

    request.allowScanningByMediaScanner();

    final DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(request);
}

From source file:com.svo.library.widget.RLWebBrowser.java

private void showMenu() {
    RLListDialog dialog = new RLListDialog(context, context.getString(R.string.select_item),
            getResources().getStringArray(R.array.webview_items), new RLListDialog.Listener() {
                @Override/*from   w  w w .  j a v  a2 s  .  co  m*/
                public void onItemClick(int position) {
                    switch (position) {
                    case 0:
                        getDownUrls(webView.getUrl());
                        RLUiUtil.toast(context, "???");
                        break;
                    case 1:
                        webView.clearCache(true);
                        RLUiUtil.toast(context, R.string.cache_cleared);
                        break;
                    case 2:
                        if (isAllowClearCookie) {
                            if (CookieManager.getInstance().hasCookies()) {
                                CookieManager.getInstance().removeAllCookie();
                                RLUiUtil.toast(context, R.string.cookie_cleared);
                            } else {
                                RLUiUtil.toast(context, R.string.has_no_cookie);
                            }
                        } else {
                            RLUiUtil.toast(context, R.string.deny_clear_cookie);
                        }
                        break;
                    case 3:
                        if (webView.canGoBack() || webView.canGoForward()) {
                            webView.clearHistory();
                            updateNaviButtonState();
                            RLUiUtil.toast(context, R.string.history_cleared);
                        } else {
                            RLUiUtil.toast(context, R.string.has_no_history);
                        }
                        break;
                    }
                }

                @Override
                public void onCancel() {
                }
            });
    dialog.show();
}

From source file:com.polyvi.xface.extension.advancedfiletransfer.XFileDownloader.java

/**
 * connectionCookie/*w ww  .  j a  va2  s. c  om*/
 * @param connection   Http
 * @param domain       cookie
 */
private void setCookieProperty(HttpURLConnection connection, String domain) {
    //Add cookie support
    mCookieSyncManager.startSync();
    String cookie = CookieManager.getInstance().getCookie(domain);
    if (cookie != null) {
        connection.setRequestProperty("cookie", cookie);
    }
}

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

@Override
protected WebView createViewInstance(final ThemedReactContext reactContext) {
    final ReactWebView webView = new ReactWebView(reactContext);

    /**//w  w w . j  a v a  2s. c om
     * cookie?
     * 5.0???cookie,5.0?false
     * 
     */
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
    }

    webView.setDownloadListener(new DownloadListener() {
        @Override
        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);
            reactContext.getCurrentActivity().startActivity(intent);

            //                DownloadManager.Request request = new DownloadManager.Request(
            //                        Uri.parse(url));
            //
            //                request.setMimeType(mimetype);
            //                String cookies = CookieManager.getInstance().getCookie(url);
            //                request.addRequestHeader("cookie", cookies);
            //                request.addRequestHeader("User-Agent", userAgent);
            //                request.allowScanningByMediaScanner();
            ////                request.setTitle()
            //                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
            //                request.setDestinationInExternalPublicDir(
            //                        Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
            //                                url, contentDisposition, mimetype));
            //                DownloadManager dm = (DownloadManager) reactContext.getCurrentActivity().getSystemService(DOWNLOAD_SERVICE);
            //                dm.enqueue(request);
            //                Toast.makeText(reactContext, "...", //To notify the Client that the file is being downloaded
            //                        Toast.LENGTH_LONG).show();

        }
    });
    webView.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onConsoleMessage(ConsoleMessage message) {
            if (ReactBuildConfig.DEBUG) {
                return super.onConsoleMessage(message);
            }
            // Ignore console logs in non debug builds.
            return true;
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(String origin,
                GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
        }

        private File createImageFile() throws IOException {
            // Create an image file name
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String imageFileName = "JPEG_" + timeStamp + "_";
            File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            File imageFile = new File(storageDir, /* directory */
                    imageFileName + ".jpg" /* filename */
            );
            return imageFile;
        }

        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                WebChromeClient.FileChooserParams fileChooserParams) {
            if (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(null);
            }
            mFilePathCallback = filePathCallback;

            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent
                    .resolveActivity(reactContext.getCurrentActivity().getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    FLog.e(ReactConstants.TAG, "Unable to create Image File", ex);
                }

                // Continue only if the File was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                } else {
                    takePictureIntent = null;
                }
            }

            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("*/*");

            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[] { takePictureIntent };
            } else {
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "?");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
            reactContext.getCurrentActivity().startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            // final Intent galleryIntent = new Intent(Intent.ACTION_PICK);
            // galleryIntent.setType("image/*");
            // final Intent chooserIntent = Intent.createChooser(galleryIntent, "Choose File");
            // reactContext.getCurrentActivity().startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {

            if (mVideoView != null) {
                callback.onCustomViewHidden();
                return;
            }

            // Store the view and it's callback for later, so we can dispose of them correctly
            mVideoView = view;
            mCustomViewCallback = callback;

            view.setBackgroundColor(Color.BLACK);
            getRootView().addView(view, FULLSCREEN_LAYOUT_PARAMS);
            webView.setVisibility(View.GONE);

            UiThreadUtil.runOnUiThread(new Runnable() {
                @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void run() {
                    // If the status bar is translucent hook into the window insets calculations
                    // and consume all the top insets so no padding will be added under the status bar.
                    View decorView = reactContext.getCurrentActivity().getWindow().getDecorView();
                    decorView.setOnApplyWindowInsetsListener(null);
                    ViewCompat.requestApplyInsets(decorView);
                }
            });

            reactContext.getCurrentActivity()
                    .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        }

        @Override
        public void onHideCustomView() {
            if (mVideoView == null) {
                return;
            }

            mVideoView.setVisibility(View.GONE);
            getRootView().removeView(mVideoView);
            mVideoView = null;
            mCustomViewCallback.onCustomViewHidden();
            webView.setVisibility(View.VISIBLE);
            //                View decorView = reactContext.getCurrentActivity().getWindow().getDecorView();
            //                // Show Status Bar.
            //                int uiOptions = View.SYSTEM_UI_FLAG_VISIBLE;
            //                decorView.setSystemUiVisibility(uiOptions);

            UiThreadUtil.runOnUiThread(new Runnable() {
                @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void run() {
                    // If the status bar is translucent hook into the window insets calculations
                    // and consume all the top insets so no padding will be added under the status bar.
                    View decorView = reactContext.getCurrentActivity().getWindow().getDecorView();
                    //                                decorView.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
                    //                                    @Override
                    //                                    public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
                    //                                        WindowInsets defaultInsets = v.onApplyWindowInsets(insets);
                    //                                        return defaultInsets.replaceSystemWindowInsets(
                    //                                                defaultInsets.getSystemWindowInsetLeft(),
                    //                                                0,
                    //                                                defaultInsets.getSystemWindowInsetRight(),
                    //                                                defaultInsets.getSystemWindowInsetBottom());
                    //                                    }
                    //                                });
                    decorView.setOnApplyWindowInsetsListener(null);
                    ViewCompat.requestApplyInsets(decorView);
                }
            });

            reactContext.getCurrentActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        }

        private ViewGroup getRootView() {
            return ((ViewGroup) reactContext.getCurrentActivity().findViewById(android.R.id.content));
        }

    });

    reactContext.addLifecycleEventListener(webView);
    reactContext.addActivityEventListener(new ActivityEventListener() {
        @Override
        public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
            if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
                return;
            }
            Uri[] results = null;

            // Check that the response is a good one
            if (resultCode == Activity.RESULT_OK) {
                if (data == null) {
                    // If there is not data, then we may have taken a photo
                    if (mCameraPhotoPath != null) {
                        results = new Uri[] { Uri.parse(mCameraPhotoPath) };
                    }
                } else {
                    String dataString = data.getDataString();
                    if (dataString != null) {
                        results = new Uri[] { Uri.parse(dataString) };
                    }
                }
            }

            if (results == null) {
                mFilePathCallback.onReceiveValue(new Uri[] {});
            } else {
                mFilePathCallback.onReceiveValue(results);
            }
            mFilePathCallback = null;
            return;
        }

        @Override
        public void onNewIntent(Intent intent) {
        }
    });
    mWebViewConfig.configWebView(webView);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setDisplayZoomControls(false);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setDefaultFontSize(16);
    webView.getSettings().setTextZoom(100);
    // Fixes broken full-screen modals/galleries due to body height being 0.
    webView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

    if (ReactBuildConfig.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(true);
    }

    return webView;
}

From source file:com.polyvi.xface.extension.advancedfiletransfer.FileDownloader.java

/**
 * connectionCookie//from   w w  w .  j  a  va 2  s  .c  om
 *
 * @param connection
 *            Http
 * @param domain
 *            cookie
 */
private void setCookieProperty(HttpURLConnection connection, String domain) {
    // Add cookie support
    mCookieSyncManager.startSync();
    String cookie = CookieManager.getInstance().getCookie(domain);
    if (cookie != null) {
        connection.setRequestProperty("cookie", cookie);
    }
}

From source file:com.microsoft.aad.adal.testapp.MainActivity.java

private void removeCookies() {
    // Clear browser cookies
    CookieSyncManager.createInstance(MainActivity.this);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.removeAllCookie();//from  ww w  . j  a v a  2 s.  c o  m
    CookieSyncManager.getInstance().sync();
}

From source file:com.citrus.sdk.CitrusActivity.java

private static void removeCookies() {
    String setCookie = CookieManager.getInstance().getCookie(Config.getBaseURL());
    CookieManager.getInstance().setCookie(Config.getBaseURL(), Constants.CITRUS_PREPAID_COOKIE);
}

From source file:de.baumann.browser.Browser_right.java

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    final WebView.HitTestResult result = mWebView.getHitTestResult();
    final String url = result.getExtra();

    if (result.getType() == WebView.HitTestResult.IMAGE_TYPE) {

        final CharSequence[] options = { getString(R.string.context_saveImage),
                getString(R.string.context_shareImage), getString(R.string.context_readLater),
                getString(R.string.context_left) };
        new AlertDialog.Builder(Browser_right.this)
                .setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                    }/*from w  w  w . j  a v a 2s .co  m*/
                }).setItems(options, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int item) {
                        if (options[item].equals(getString(R.string.context_saveImage))) {
                            if (url != null) {
                                try {
                                    Uri source = Uri.parse(url);
                                    DownloadManager.Request request = new DownloadManager.Request(source);
                                    request.addRequestHeader("Cookie",
                                            CookieManager.getInstance().getCookie(url));
                                    request.allowScanningByMediaScanner();
                                    request.setNotificationVisibility(
                                            DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
                                    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                                            helper_main.newFileName());
                                    DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                                    dm.enqueue(request);
                                    Snackbar.make(mWebView, getString(R.string.context_saveImage_toast) + " "
                                            + helper_main.newFileName(), Snackbar.LENGTH_SHORT).show();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    Snackbar.make(mWebView, R.string.toast_perm, Snackbar.LENGTH_SHORT).show();
                                }
                            }
                        }
                        if (options[item].equals(getString(R.string.context_shareImage))) {
                            if (url != null) {

                                shareString = helper_main.newFileName();
                                shareFile = helper_main.newFile(mWebView);

                                try {
                                    Uri source = Uri.parse(url);
                                    DownloadManager.Request request = new DownloadManager.Request(source);
                                    request.addRequestHeader("Cookie",
                                            CookieManager.getInstance().getCookie(url));
                                    request.allowScanningByMediaScanner();
                                    request.setNotificationVisibility(
                                            DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
                                    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                                            shareString);
                                    DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                                    dm.enqueue(request);

                                    Snackbar.make(mWebView, getString(R.string.context_saveImage_toast) + " "
                                            + helper_main.newFileName(), Snackbar.LENGTH_SHORT).show();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    Snackbar.make(mWebView, R.string.toast_perm, Snackbar.LENGTH_SHORT).show();
                                }
                                registerReceiver(onComplete2,
                                        new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
                            }
                        }
                        if (options[item].equals(getString(R.string.context_readLater))) {
                            if (url != null) {

                                if (Uri.parse(url).getHost().length() == 0) {
                                    domain = getString(R.string.app_domain);
                                } else {
                                    domain = Uri.parse(url).getHost();
                                }

                                String domain2 = domain.substring(0, 1).toUpperCase() + domain.substring(1);

                                DbAdapter_ReadLater db = new DbAdapter_ReadLater(Browser_right.this);
                                db.open();
                                if (db.isExist(mWebView.getUrl())) {
                                    Snackbar.make(editText, getString(R.string.toast_newTitle),
                                            Snackbar.LENGTH_LONG).show();
                                } else {
                                    db.insert(domain2, url, "", "", helper_main.createDate());
                                    Snackbar.make(mWebView, R.string.bookmark_added, Snackbar.LENGTH_LONG)
                                            .show();
                                }
                            }
                        }
                        if (options[item].equals(getString(R.string.context_left))) {
                            if (url != null) {
                                helper_main.switchToActivity(Browser_right.this, Browser_left.class, url,
                                        false);
                            }
                        }
                    }
                }).show();

    } else if (result.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE) {

        final CharSequence[] options = { getString(R.string.menu_share_link_copy),
                getString(R.string.menu_share_link), getString(R.string.context_readLater),
                getString(R.string.context_left) };
        new AlertDialog.Builder(Browser_right.this)
                .setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                    }
                }).setItems(options, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int item) {
                        if (options[item].equals(getString(R.string.menu_share_link_copy))) {
                            if (url != null) {
                                ClipboardManager clipboard = (ClipboardManager) Browser_right.this
                                        .getSystemService(Context.CLIPBOARD_SERVICE);
                                clipboard.setPrimaryClip(ClipData.newPlainText("text", url));
                                Snackbar.make(mWebView, R.string.context_linkCopy_toast, Snackbar.LENGTH_SHORT)
                                        .show();
                            }
                        }
                        if (options[item].equals(getString(R.string.menu_share_link))) {
                            if (url != null) {
                                Intent sendIntent = new Intent();
                                sendIntent.setAction(Intent.ACTION_SEND);
                                sendIntent.putExtra(Intent.EXTRA_TEXT, url);
                                sendIntent.setType("text/plain");
                                Browser_right.this.startActivity(Intent.createChooser(sendIntent,
                                        getResources().getString(R.string.app_share_link)));
                            }
                        }
                        if (options[item].equals(getString(R.string.context_readLater))) {
                            if (url != null) {

                                if (Uri.parse(url).getHost().length() == 0) {
                                    domain = getString(R.string.app_domain);
                                } else {
                                    domain = Uri.parse(url).getHost();
                                }

                                String domain2 = domain.substring(0, 1).toUpperCase() + domain.substring(1);

                                DbAdapter_ReadLater db = new DbAdapter_ReadLater(Browser_right.this);
                                db.open();
                                if (db.isExist(mWebView.getUrl())) {
                                    Snackbar.make(editText, getString(R.string.toast_newTitle),
                                            Snackbar.LENGTH_LONG).show();
                                } else {
                                    db.insert(domain2, url, "", "", helper_main.createDate());
                                    Snackbar.make(mWebView, R.string.bookmark_added, Snackbar.LENGTH_LONG)
                                            .show();
                                }
                            }
                        }
                        if (options[item].equals(getString(R.string.context_left))) {
                            if (url != null) {
                                helper_main.switchToActivity(Browser_right.this, Browser_left.class, url,
                                        false);
                            }
                        }
                    }
                }).show();
    }
}