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:org.microg.gms.auth.login.LoginActivity.java

private void init() {
    setTitle(R.string.just_a_sec);//  ww  w .  j  a  va2 s . com
    setBackButtonText(null);
    setNextButtonText(null);
    View loading = getLayoutInflater().inflate(R.layout.login_assistant_loading, authContent, false);
    authContent.removeAllViews();
    authContent.addView(loading);
    setMessage(R.string.auth_connecting);
    CookieManager.getInstance().setAcceptCookie(true);
    if (SDK_INT >= LOLLIPOP) {
        CookieManager.getInstance().removeAllCookies(new ValueCallback<Boolean>() {
            @Override
            public void onReceiveValue(Boolean value) {
                start();
            }
        });
    } else {
        //noinspection deprecation
        CookieManager.getInstance().removeAllCookie();
        start();
    }
}

From source file:br.com.ufc.palestrasufc.twitter.Util.java

public static void clearCookies(Context context) {
    // Edge case: an illegal state exception is thrown if an instance of 
    // CookieSyncManager has not be created.  CookieSyncManager is normally
    // created by a WebKit view, but this might happen if you start the 
    // app, restore saved state, and click logout before running a UI 
    // dialog in a WebView -- in which case the app crashes
    @SuppressWarnings("unused")
    CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(context);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.removeAllCookie();//from  w  w  w .  ja v a  2s.  co  m
}

From source file:com.owncloud.android.ui.dialog.LoginWebViewDialog.java

@SuppressWarnings("deprecation")
@SuppressLint("SetJavaScriptEnabled")
@Override/*from  w w w  . j a  va2 s . co  m*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Log_OC.v(TAG, "onCreateView, savedInsanceState is " + savedInstanceState);

    // Inflate layout of the dialog  
    RelativeLayout ssoRootView = (RelativeLayout) inflater.inflate(R.layout.webview_dialog, container, false); // null parent view because it will go in the dialog layout

    if (mWebView == null) {
        // initialize the WebView
        mWebView = new SsoWebView(getActivity().getApplicationContext());
        mWebView.setFocusable(true);
        mWebView.setFocusableInTouchMode(true);
        mWebView.setClickable(true);

        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSavePassword(false);
        webSettings.setUserAgentString(MainApp.getUserAgent());
        webSettings.setSaveFormData(false);
        // next two settings grant that non-responsive webs are zoomed out when loaded
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        // next three settings allow the user use pinch gesture to zoom in / out
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDisplayZoomControls(false);
        webSettings.setAllowFileAccess(false);

        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeAllCookie();

        mWebView.loadUrl(mInitialUrl);
    }

    mWebViewClient.addTargetUrls(mTargetUrls);
    mWebView.setWebViewClient(mWebViewClient);

    // add the webview into the layout
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
    ssoRootView.addView(mWebView, layoutParams);
    ssoRootView.requestLayout();

    return ssoRootView;
}

From source file:com.acrutiapps.browser.ui.components.CustomWebView.java

@SuppressLint("SetJavaScriptEnabled")
public void loadSettings() {
    WebSettings settings = getSettings();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());

    settings.setJavaScriptEnabled(prefs.getBoolean(Constants.PREFERENCE_ENABLE_JAVASCRIPT, true));
    settings.setLoadsImagesAutomatically(prefs.getBoolean(Constants.PREFERENCE_ENABLE_IMAGES, true));
    settings.setUseWideViewPort(prefs.getBoolean(Constants.PREFERENCE_USE_WIDE_VIEWPORT, true));
    settings.setLoadWithOverviewMode(prefs.getBoolean(Constants.PREFERENCE_LOAD_WITH_OVERVIEW, false));

    settings.setGeolocationEnabled(prefs.getBoolean(Constants.PREFERENCE_ENABLE_GEOLOCATION, true));
    settings.setSaveFormData(prefs.getBoolean(Constants.PREFERENCE_REMEMBER_FORM_DATA, true));
    settings.setSavePassword(prefs.getBoolean(Constants.PREFERENCE_REMEMBER_PASSWORDS, true));

    settings.setTextZoom(prefs.getInt(Constants.PREFERENCE_TEXT_SCALING, 100));

    int minimumFontSize = prefs.getInt(Constants.PREFERENCE_MINIMUM_FONT_SIZE, 1);
    settings.setMinimumFontSize(minimumFontSize);
    settings.setMinimumLogicalFontSize(minimumFontSize);

    boolean useInvertedDisplay = prefs.getBoolean(Constants.PREFERENCE_INVERTED_DISPLAY, false);
    setWebSettingsProperty(settings, "inverted", useInvertedDisplay ? "true" : "false");

    if (useInvertedDisplay) {
        setWebSettingsProperty(settings, "inverted_contrast",
                Float.toString(prefs.getInt(Constants.PREFERENCE_INVERTED_DISPLAY_CONTRAST, 100) / 100f));
    }/*from  w ww .  jav a2  s . c  om*/

    settings.setUserAgentString(prefs.getString(Constants.PREFERENCE_USER_AGENT, Constants.USER_AGENT_ANDROID));
    settings.setPluginState(PluginState
            .valueOf(prefs.getString(Constants.PREFERENCE_PLUGINS, PluginState.ON_DEMAND.toString())));

    CookieManager.getInstance().setAcceptCookie(prefs.getBoolean(Constants.PREFERENCE_ACCEPT_COOKIES, true));

    settings.setSupportZoom(true);
    settings.setDisplayZoomControls(false);
    settings.setBuiltInZoomControls(true);
    settings.setSupportMultipleWindows(true);
    settings.setEnableSmoothTransition(true);

    if (mPrivateBrowsing) {
        settings.setGeolocationEnabled(false);
        settings.setSaveFormData(false);
        settings.setSavePassword(false);

        settings.setAppCacheEnabled(false);
        settings.setDatabaseEnabled(false);
        settings.setDomStorageEnabled(false);
    } else {
        // HTML5 API flags
        settings.setAppCacheEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setDomStorageEnabled(true);

        // HTML5 configuration settings.
        settings.setAppCacheMaxSize(3 * 1024 * 1024);
        settings.setAppCachePath(mContext.getDir("appcache", 0).getPath());
        settings.setDatabasePath(mContext.getDir("databases", 0).getPath());
        settings.setGeolocationDatabasePath(mContext.getDir("geolocation", 0).getPath());
    }

    setLongClickable(true);
    setDownloadListener(this);
}

From source file:com.popdeem.sdk.uikit.fragment.PDUIInstagramLoginFragment.java

@SuppressWarnings("deprecation")
private void clearCookies() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
        CookieManager.getInstance().removeAllCookies(null);
        CookieManager.getInstance().flush();
    } else {//w w  w  .ja v a2  s .  co m
        CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(getActivity());
        cookieSyncManager.startSync();
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
        cookieManager.removeSessionCookie();
        cookieSyncManager.stopSync();
        cookieSyncManager.sync();
    }
}

From source file:de.baumann.hhsmoodle.fragmentsMain.FragmentBrowser.java

@SuppressWarnings("ResultOfMethodCallIgnored")
@SuppressLint("SetJavaScriptEnabled")

@Override//from www.  j ava 2  s  . c  o m
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_screen_browser, container, false);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        WebView.enableSlowWholeDocumentDraw();
    }

    PreferenceManager.setDefaultValues(getActivity(), R.xml.user_settings, false);
    sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
    sharedPref.edit().putString("browserStarted", "true").apply();

    customViewContainer = (FrameLayout) rootView.findViewById(R.id.customViewContainer);
    progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);
    viewPager = (ViewPager) getActivity().findViewById(R.id.viewpager);

    SwipeRefreshLayout swipeView = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe);
    assert swipeView != null;
    swipeView.setColorSchemeResources(R.color.colorPrimary, R.color.colorAccent);
    swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mWebView.reload();
        }
    });

    mWebView = (WebView) rootView.findViewById(R.id.webView);
    mWebChromeClient = new myWebChromeClient();
    mWebView.setWebChromeClient(mWebChromeClient);

    imageButton_left = (ImageButton) rootView.findViewById(R.id.imageButton_left);
    imageButton_right = (ImageButton) rootView.findViewById(R.id.imageButton_right);

    if (sharedPref.getBoolean("arrow", false)) {
        imageButton_left.setVisibility(View.VISIBLE);
        imageButton_right.setVisibility(View.VISIBLE);
    } else {
        imageButton_left.setVisibility(View.INVISIBLE);
        imageButton_right.setVisibility(View.INVISIBLE);
    }

    helper_webView.webView_Settings(getActivity(), mWebView);
    helper_webView.webView_WebViewClient(getActivity(), swipeView, mWebView);

    mWebView.setDownloadListener(new DownloadListener() {

        public void onDownloadStart(final String url, String userAgent, final String contentDisposition,
                final String mimetype, long contentLength) {

            final String filename = URLUtil.guessFileName(url, contentDisposition, mimetype);
            Snackbar snackbar = Snackbar
                    .make(mWebView, getString(R.string.toast_download_1) + " " + filename,
                            Snackbar.LENGTH_INDEFINITE)
                    .setAction(getString(R.string.toast_yes), new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                            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(newFileDest(), filename);
                            DownloadManager dm = (DownloadManager) getActivity()
                                    .getSystemService(DOWNLOAD_SERVICE);
                            dm.enqueue(request);

                            Snackbar.make(mWebView, getString(R.string.toast_download) + " " + filename,
                                    Snackbar.LENGTH_LONG).show();
                            getActivity().registerReceiver(onComplete,
                                    new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
                        }
                    });
            snackbar.show();
        }
    });

    String URLtoOpen = sharedPref.getString("loadURL", "");
    if (URLtoOpen.isEmpty()) {
        mWebView.loadUrl(
                sharedPref.getString("favoriteURL", "https://moodle.huebsch.ka.schule-bw.de/moodle/my/"));
    } else {
        mWebView.loadUrl(URLtoOpen);
    }

    setHasOptionsMenu(true);
    return rootView;
}

From source file:com.social_api.facebook.core.Util.java

public static void clearCookies(Context context) {
    // Edge case: an illegal state exception is thrown if an instance of
    // CookieSyncManager has not be created.  CookieSyncManager is normally
    // created by a WebKit view, but this might happen if you hasStarted the
    // app, restore saved state, and click logout before running a UI
    // dialog in a WebView -- in which case the app crashes
    @SuppressWarnings("unused")
    CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(context);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.removeAllCookie();//from w w w .j a  v  a 2 s. c o  m
}

From source file:com.polyvi.xface.extension.xmlhttprequest.XXMLHttpRequest.java

/**
 * cookie//  w  w w. ja va 2s  . com
 * 
 * @param url
 *            url?
 */
private void addCookie(String url) {
    // cookie?
    CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(mContext);
    cookieSyncManager.startSync();
    String cookie = CookieManager.getInstance().getCookie(url);
    if (cookie != null) {
        mRequestHeaders.put("Cookie", cookie);
    }
}

From source file:com.captix.scan.social.facebook.Util.java

public static void clearCookies(Context context) {
    // Edge case: an illegal state exception is thrown if an instance of
    // CookieSyncManager has not be created. CookieSyncManager is normally
    // created by a WebKit view, but this might happen if you start the
    // app, restore saved state, and click logout before running a UI
    // dialog in a WebView -- in which case the app crashes
    @SuppressWarnings("unused")
    CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(context);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.removeAllCookie();/*from  w w  w .ja  v  a2 s .co  m*/
}

From source file:at.ac.uniklu.mobile.sportal.WebViewActivity.java

@SuppressLint("SetJavaScriptEnabled")
@Override/*from   w ww  .j a  v  a2  s.  c  o m*/
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String targetUrl = getIntent().getStringExtra(URL);
    if (targetUrl == null || targetUrl.length() == 0) {
        // if there's no URL, close the activity
        finish();
    }

    setContentView(R.layout.webview);
    mActionBar = new ActionBarHelper(this).setupHeader().addActionRefresh();

    // set header title or hide header if no title is given
    String title = getIntent().getStringExtra(TITLE);
    if (title != null) {
        ((TextView) findViewById(R.id.view_title)).setText(title);
    } else {
        findViewById(R.id.actionbar).setVisibility(View.GONE);
    }

    // Moodle 2.0 uses SSO/CAS authentication
    mSSO = getIntent().getBooleanExtra(SSO, false);

    // the moodle hack is only needed until Android 2.3 (or maybe 3.x? - not tested)
    // Android 4.0 has the redirect history entry problem solved
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.GINGERBREAD_MR1) {
        mExecuteMoodleHack = getIntent().getBooleanExtra(MOODLE_HACK, false);
    }

    mWebView = (WebView) findViewById(R.id.web_view);
    //mWebView.setBackgroundColor(Color.BLACK); // black color messes up the CAS login page
    mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); // http://stackoverflow.com/questions/3998916/android-webview-leaves-space-for-scrollbar
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setLightTouchEnabled(true);
    mWebView.getSettings().setLoadWithOverviewMode(true);
    mWebView.getSettings().setBuiltInZoomControls(true);
    mWebView.getSettings().setUseWideViewPort(true);

    // setup custom webview client that shows a progress dialog while loading
    mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("https://sso.uni-klu.ac.at") || url.startsWith("https://sso.aau.at")
                    || url.startsWith("https://campus.aau.at") || url.startsWith("https://moodle.aau.at")) {
                return false;
            } else if (url.startsWith("http://campus-gis.aau.at/")) {
                Log.d(TAG, "REDIRECT TO MAP");
                String roomParameter = "curRouteTo=";
                int index = url.indexOf(roomParameter);
                if (index > -1) {
                    MapUtils.openMapAndShowRoom(WebViewActivity.this,
                            url.substring(index + roomParameter.length()));
                }
                return true;
            }

            // open external websites in browser
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(url));
            startActivity(i);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            progressNotificationOn();
            super.onPageStarted(view, url, favicon);
        }

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

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            progressNotificationOff();

            /*
             *  the first page of moodle opens through a redirect so we need to clear the first history
             *  entry to avoid execution of the redirect when going back through the history with the back button
             */
            if (mExecuteMoodleHack && mWebView.canGoBack()) {
                mWebView.clearHistory();
                mExecuteMoodleHack = false;
            } else {
                mIsFirstPage = false;
            }
        }
    });

    mWebView.setDownloadListener(new DownloadListener() {
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                long contentLength) {
            Analytics.onEvent(Analytics.EVENT_WEB_COURSEMOODLE_DOWNLOAD);
            Uri uri = Uri.parse(url);
            MoodleDownloadHelper.download(WebViewActivity.this, uri,
                    Utils.getContentDispositionOrUrlFilename(contentDisposition, uri));
        }
    });

    // set session cookie
    // http://stackoverflow.com/questions/1652850/android-webview-cookie-problem
    // http://android.joao.jp/2010/11/cookiemanager-and-removeallcookie.html
    if (Studentportal.getSportalClient().isSessionCookieAvailable()) {
        CookieSyncManager.createInstance(this);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        //cookieManager.removeSessionCookie(); // NOTE when calling this method the cookies get removed after the next setCookie() gets called

        Cookie sessionCookie = Studentportal.getSportalClient().getSessionCookie();
        cookieManager.setCookie(sessionCookie.getDomain(), Utils.cookieHeaderString(sessionCookie));

        if (mSSO) {
            // set SSO/CAS cookie
            Cookie ssoCookie = Studentportal.getSportalClient().getCookie("CASTGC");
            if (ssoCookie != null) {
                cookieManager.setCookie(ssoCookie.getDomain(), Utils.cookieHeaderString(ssoCookie));
            }
        }

        CookieSyncManager.getInstance().sync();
    }

    mIsFirstPage = true;
    mWebView.loadUrl(targetUrl);
}