Example usage for android.webkit CookieSyncManager createInstance

List of usage examples for android.webkit CookieSyncManager createInstance

Introduction

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

Prototype

public static CookieSyncManager createInstance(Context context) 

Source Link

Document

Create a singleton CookieSyncManager within a context

Usage

From source file:com.microsoft.firstapp.AuthService.java

/**
 * Handles logging the user out including: -deleting cookies so their login
 * with a provider won't be cached in the web view -removing the userdata
 * from the shared preferences -setting the current user object on the
 * client to logged out -optionally redirects to the login page if requested
 * //w w w .  ja  va  2 s . c o m
 * @param shouldRedirectToLogin
 */
public void logout(boolean shouldRedirectToLogin) {
    // Clear the cookies so they won't auto login to a provider again
    CookieSyncManager.createInstance(mContext);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.removeAllCookie();
    // Clear the user id and token from the shared preferences
    SharedPreferences settings = mContext.getSharedPreferences("UserData", 0);
    SharedPreferences.Editor preferencesEditor = settings.edit();
    preferencesEditor.clear();
    preferencesEditor.commit();
    // Clear the user and return to the auth activity
    mClient.logout();
    // Take the user back to the auth activity to relogin if requested
    if (shouldRedirectToLogin) {
        Intent logoutIntent = new Intent(mContext, LogInActivity.class);
        logoutIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(logoutIntent);
    }
}

From source file:com.eTilbudsavis.etasdk.SessionManager.java

private void postSession(final Listener<JSONObject> l) {

    Map<String, Object> args = new HashMap<String, Object>();

    args.put(Param.TOKEN_TTL, TTL);/*w  ww .  jav  a  2  s.c  om*/
    args.put(Param.API_KEY, mEta.getApiKey());

    CookieSyncManager.createInstance(mEta.getContext());
    CookieManager cm = CookieManager.getInstance();
    String cookieString = cm.getCookie(ETA_COOKIE_DOMAIN);

    if (cookieString != null) {

        // No session yet, check cookies for old token
        String authId = null;
        String authTime = null;
        String authHash = null;

        String[] cookies = cookieString.split(";");
        for (String cookie : cookies) {

            String[] keyValue = cookie.split("=");
            String key = keyValue[0].trim();
            String value = keyValue[1];

            if (value.equals("")) {
                continue;
            }

            if (key.equals(COOKIE_AUTH_ID)) {
                authId = value;
            } else if (key.equals(COOKIE_AUTH_HASH)) {
                authHash = value;
            } else if (key.equals(COOKIE_AUTH_TIME)) {
                authTime = value;
            }

        }

        // If all three fields are set, then try to migrate
        if (authId != null && authHash != null && authTime != null) {
            args.put(Param.V1_AUTH_ID, authId);
            args.put(Param.V1_AUTH_HASH, authHash);
            args.put(Param.V1_AUTH_TIME, authTime);
        }

        // Clear all cookie data, just to make sure
        cm.removeAllCookie();

    }

    JsonObjectRequest req = new JsonObjectRequest(Method.POST, Endpoint.SESSIONS, new JSONObject(args),
            getSessionListener(l));
    addRequest(req);

}

From source file:com.example.sabeeh.helloworld.AuthService.java

/**
 * Handles logging the user out including:
 * -deleting cookies so their login with a provider won't be cached in the web view
 * -removing the userdata from the shared preferences
 * -setting the current user object on the client to logged out
 * -optionally redirects to the login page if requested
 * @param shouldRedirectToLogin//from   w w  w  . jav a2 s.c o  m
 */
public void logout(boolean shouldRedirectToLogin) {
    //Clear the cookies so they won't auto login to a provider again
    CookieSyncManager.createInstance(mContext);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.removeAllCookie();
    //Clear the user id and token from the shared preferences
    ClearcacheUserToken();
    //Clear the user and return to the auth activity
    mClient.logout();
    //Take the user back to the auth activity to relogin if requested
    if (shouldRedirectToLogin) {
        Intent logoutIntent = new Intent(mContext, LoginActivity.class);
        logoutIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(logoutIntent);
    }
}

From source file:com.iStudy.Study.Renren.Util.java

public static void clearCookies(Context context) {
    @SuppressWarnings("unused")
    CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(context);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.removeAllCookie();/*from   www .ja  v a  2  s . c  om*/
}

From source file:com.company.millenium.iwannask.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //GPS//from   w  ww  . j a  v  a2 s .  c  om
    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            if (ActivityCompat.checkSelfPermission(MainActivity.this,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // Check Permissions Now
                final int REQUEST_LOCATION = 2;

                if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                        Manifest.permission.ACCESS_FINE_LOCATION)) {
                    // Display UI and wait for user interaction
                } else {
                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION);
                }
            } else {
                locationManager.removeUpdates(this);
            }
        }

        public void onStatusChanged(String string, int integer, Bundle bundle) {

        }

        public void onProviderEnabled(String string) {

        }

        public void onProviderDisabled(String string) {

        }
    };

    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // Check Permissions Now
        final int REQUEST_LOCATION = 2;

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            // Display UI and wait for user interaction
        } else {
            ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
                    REQUEST_LOCATION);
        }
    } else {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1000, locationListener);
    }

    int delay = 30000; // delay for 30 sec.
    int period = 3000000; // repeat every 5.3min.
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            if (ActivityCompat.checkSelfPermission(MainActivity.this,
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // Check Permissions Now
                final int REQUEST_LOCATION = 2;

                if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                        Manifest.permission.ACCESS_FINE_LOCATION)) {
                    // Display UI and wait for user interaction
                } else {
                    ActivityCompat.requestPermissions(MainActivity.this,
                            new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_LOCATION);
                }
            } else {
                locationManager.removeUpdates(locationListener);
            }
        }
    }, delay, period);

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);

    Intent mIntent = getIntent();
    URL = Constants.SERVER_URL;
    if (mIntent.hasExtra("url")) {
        myWebView = null;
        startActivity(getIntent());
        String url = mIntent.getStringExtra("url");
        URL = Constants.SERVER_URL + url;
    }

    CookieSyncManager.createInstance(this);
    CookieSyncManager.getInstance().startSync();
    myWebView = (WebView) findViewById(R.id.webview);
    myWebView.getSettings().setGeolocationDatabasePath(this.getFilesDir().getPath());
    myWebView.getSettings().setGeolocationEnabled(true);
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setUseWideViewPort(false);
    if (!DetectConnection.checkInternetConnection(this)) {
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        showNoConnectionDialog(this);
    } else {
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
    }
    webSettings.setJavaScriptEnabled(true);
    myWebView.addJavascriptInterface(new webappinterface(this), "android");
    webSettings.setLoadWithOverviewMode(true);
    webSettings.setUseWideViewPort(true);
    myWebView.setOverScrollMode(View.OVER_SCROLL_NEVER);

    //location test
    webSettings.setAppCacheEnabled(true);
    webSettings.setDatabaseEnabled(true);
    webSettings.setDomStorageEnabled(true);

    myWebView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            CookieSyncManager.getInstance().sync();
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed(); // Ignore SSL certificate errors
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (Uri.parse(url).getHost().equals(Constants.HOST)
                    || Uri.parse(url).getHost().equals(Constants.WWWHOST)) {
                // This is my web site, so do not override; let my WebView load
                // the page
                return false;
            }
            // Otherwise, the link is not for a page on my site, so launch
            // another Activity that handles URLs
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            return true;
        }
    });
    myWebView.setWebChromeClient(new WebChromeClient() {
        public void onGeolocationPermissionsShowPrompt(String origin,
                GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
        }

        @Override
        public void onPermissionRequest(final PermissionRequest request) {
            Log.d(TAG, "onPermissionRequest");
            runOnUiThread(new Runnable() {
                @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void run() {
                    if (request.getOrigin().toString().equals("https://apprtc-m.appspot.com/")) {
                        request.grant(request.getResources());
                    } else {
                        request.deny();
                    }
                }
            });
        }

        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                WebChromeClient.FileChooserParams fileChooserParams) {

            // Double check that we don't have any existing callbacks
            if (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(null);
            }
            mFilePathCallback = filePathCallback;

            // Set up the take picture intent
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(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
                    Log.e(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;
                }
            }

            // Set up the intent to get an existing image
            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image/*");

            // Set up the intents for the Intent chooser
            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, "Image Chooser");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }

    });
    // setContentView(myWebView);
    //        myWebView.loadUrl(URL);
    myWebView.loadUrl(URL);
    mRegistrationBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //                mRegistrationProgressBar.setVisibility(ProgressBar.GONE);
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            boolean sentToken = sharedPreferences.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false);
        }
    };

    //CookieManager mCookieManager = CookieManager.getInstance();
    //Boolean hasCookies = mCookieManager.hasCookies();
    //while(!hasCookies);

    if (checkPlayServices()) {
        // Start IntentService to register this application with GCM.
        Intent intent = new Intent(this, RegistrationIntentService.class);
        //intent.putExtra("session", session);
        startService(intent);
    }

    Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("isFirstRun", true);

    if (isFirstRun) {
        //show start activity
        startActivity(new Intent(MainActivity.this, MyIntro.class));
    }
    //if (!isOnline())
    //    showNoConnectionDialog(this);
    getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit().putBoolean("isFirstRun", false).commit();

    //Pull-to-refresh
    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.container);
    mSwipeRefreshLayout.setOnRefreshListener(this);
}

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

public void onClickClearCookies(View view) {
    CookieSyncManager.createInstance(MainActivity.this);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.removeAllCookie();//from  w w w.j a v  a 2s  . co  m
    CookieSyncManager.getInstance().sync();
}

From source file:com.msted.lensrocket.LensRocketService.java

public void logout(boolean shouldRedirectToLogin) {
    //Clear values
    mFriendNames.clear();// ww  w .jav  a  2s  .co  m
    mFriends.clear();
    mRockets.clear();
    //Clear the cookies so they won't auto login to a provider again
    CookieSyncManager.createInstance(mContext);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.removeAllCookie();
    //Clear the user id and token from the shared preferences
    SharedPreferences settings = mContext.getSharedPreferences("UserData", 0);
    SharedPreferences.Editor preferencesEditor = settings.edit();
    preferencesEditor.clear();
    preferencesEditor.commit();

    //Clear settings shared preferences
    SharedPreferences settingsPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
    if (settingsPrefs != null) {
        preferencesEditor = settingsPrefs.edit();
        preferencesEditor.clear();
        preferencesEditor.commit();
    }
    mClient.logout();
    //Take the user back to the splash screen activity to relogin if requested
    if (shouldRedirectToLogin) {
        Intent logoutIntent = new Intent(mContext, SplashScreenActivity.class);
        logoutIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(logoutIntent);
    }
}

From source file:com.near.chimerarevo.fragments.CommentsFragment.java

@SuppressLint("SetJavaScriptEnabled")
private void loadDisqusOAuth() {
    if (getActivity().getSharedPreferences(Constants.PREFS_TAG, Context.MODE_PRIVATE)
            .getString(Constants.KEY_REFRESH_TOKEN, "").length() > 1) {

        RequestBody formBody = new FormEncodingBuilder().add("grant_type", "refresh_token")
                .add("client_id", Constants.DISQUS_API_KEY).add("client_secret", Constants.DISQUS_API_SECRET)
                .add("refresh_token",
                        getActivity().getSharedPreferences(Constants.PREFS_TAG, Context.MODE_PRIVATE)
                                .getString(Constants.KEY_REFRESH_TOKEN, ""))
                .build();/*from   w  w  w  .ja v a 2 s .c o m*/

        Request request = new Request.Builder().url(Constants.DISQUS_TOKEN_URL).post(formBody).tag(FRAGMENT_TAG)
                .build();

        if (mDialog == null)
            mDialog = ProgressDialogUtils.getInstance(getActivity(), R.string.text_login);
        else
            mDialog = ProgressDialogUtils.modifyInstance(mDialog, R.string.text_login);

        mDialog.show();
        OkHttpUtils.getInstance().newCall(request).enqueue(new PostAccessTokenCallback());

        return;
    }

    final Dialog dialog = new Dialog(getActivity());

    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.webview_layout);
    dialog.setCancelable(true);

    dialog.setOnCancelListener(new OnCancelListener() {
        @Override
        public void onCancel(DialogInterface arg0) {
            isDialogOpen = false;
            mFab.show();
        }
    });
    dialog.setOnDismissListener(new OnDismissListener() {
        @Override
        public void onDismiss(DialogInterface arg0) {
            isDialogOpen = false;
            mFab.show();
        }
    });

    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT)
        CookieManager.getInstance().removeAllCookies(null);
    else {
        CookieSyncManager.createInstance(getActivity());
        CookieManager.getInstance().removeAllCookie();
    }

    WebView wv = (WebView) dialog.findViewById(R.id.webview);
    wv.getSettings().setJavaScriptEnabled(true);
    wv.getSettings().setSaveFormData(false);
    wv.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            dialog.findViewById(R.id.progressContainer).setVisibility(View.GONE);
            dialog.findViewById(R.id.webViewContainer).setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            dialog.findViewById(R.id.progressContainer).setVisibility(View.VISIBLE);
            dialog.findViewById(R.id.webViewContainer).setVisibility(View.GONE);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            boolean state = super.shouldOverrideUrlLoading(view, url);
            if (url.contains(Constants.SITE_URL)) {
                String code = url.split("code=")[1];

                RequestBody formBody = new FormEncodingBuilder().add("grant_type", "authorization_code")
                        .add("client_id", Constants.DISQUS_API_KEY)
                        .add("client_secret", Constants.DISQUS_API_SECRET)
                        .add("redirect_uri", Constants.SITE_URL).add("code", code).build();

                Request request = new Request.Builder().url(Constants.DISQUS_TOKEN_URL).post(formBody)
                        .tag(FRAGMENT_TAG).build();

                if (mDialog == null)
                    mDialog = ProgressDialogUtils.getInstance(getActivity(), R.string.text_login);
                else
                    mDialog = ProgressDialogUtils.modifyInstance(mDialog, R.string.text_login);

                dialog.dismiss();
                mDialog.show();

                OkHttpUtils.getInstance().newCall(request).enqueue(new PostAccessTokenCallback());
            }
            return state;
        }

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

    });
    wv.loadUrl(URLUtils.getDisqusAuthUrl());

    isDialogOpen = true;
    mFab.hide();
    dialog.show();
}

From source file:org.nypl.simplified.app.MainSettingsAccountActivity.java

@Override
public void onAccountLogoutSuccess() {
    LOG.debug("onAccountLogoutSuccess");
    this.onAccountIsNotLoggedIn();

    this.annotationsManager = null;

    //if current account ??
    final SimplifiedCatalogAppServicesType app = Simplified.getCatalogAppServices();
    app.getBooks().destroyBookStatusCache();

    Simplified.getCatalogAppServices().reloadCatalog(true, this.account);
    final Resources rr = NullCheck.notNull(this.getResources());
    final Context context = this.getApplicationContext();
    final CharSequence text = NullCheck.notNull(rr.getString(R.string.settings_logout_succeeded));
    final int duration = Toast.LENGTH_SHORT;

    final TextView bt = NullCheck.notNull(this.barcode_text);
    final TextView pt = NullCheck.notNull(this.pin_text);

    UIThread.runOnUIThread(() -> {/*from   w  w w  .  jav a 2  s  .  c  om*/
        bt.setVisibility(View.GONE);
        pt.setVisibility(View.GONE);

        final Toast toast = Toast.makeText(context, text, duration);
        toast.show();
        finish();
        overridePendingTransition(0, 0);
        startActivity(getIntent());
        overridePendingTransition(0, 0);
    });

    // logout clever

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

        CookieManager.getInstance().removeAllCookies(null);
        CookieManager.getInstance().flush();
    } else {
        final CookieSyncManager cookie_sync_manager = CookieSyncManager.createInstance(this);
        cookie_sync_manager.startSync();
        final CookieManager cookie_manager = CookieManager.getInstance();
        cookie_manager.removeAllCookie();
        cookie_manager.removeSessionCookie();
        cookie_sync_manager.stopSync();
        cookie_sync_manager.sync();
    }
}