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:in.shick.diode.reddits.PickSubredditActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mSubredditsList = new ArrayList<SubredditInfo>();

    CookieSyncManager.createInstance(getApplicationContext());

    mSettings.loadRedditPreferences(this, mClient);
    setRequestedOrientation(mSettings.getRotation());
    requestWindowFeature(Window.FEATURE_PROGRESS);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

    setTheme(mSettings.getTheme());/*from   w w  w  . j a v  a2 s.com*/
    setContentView(R.layout.pick_subreddit_view);
    registerForContextMenu(getListView());

    mSubredditsList = getCachedSubredditsList();

    if (CollectionUtils.isEmpty(mSubredditsList))
        restoreLastNonConfigurationInstance();

    if (CollectionUtils.isEmpty(mSubredditsList)) {
        new DownloadRedditsTask().execute();
    } else {
        resetUI(new PickSubredditAdapter(this, mSubredditsList));
    }
}

From source file:com.andrewshu.android.reddit.submit.SubmitLinkActivity.java

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

    CookieSyncManager.createInstance(getApplicationContext());

    mSettings.loadRedditPreferences(this, mClient);
    setRequestedOrientation(mSettings.getRotation());
    setTheme(mSettings.getTheme());/*w  w w .j av a2s .  c o m*/

    setContentView(R.layout.submit_link_main);

    final FrameLayout fl = (FrameLayout) findViewById(android.R.id.tabcontent);
    if (Util.isLightTheme(mSettings.getTheme())) {
        fl.setBackgroundResource(R.color.gray_75);
    } else {
        fl.setBackgroundResource(R.color.black);
    }

    mTabHost = getTabHost();
    mTabHost.addTab(
            mTabHost.newTabSpec(Constants.TAB_LINK).setIndicator("link").setContent(R.id.submit_link_view));
    mTabHost.addTab(
            mTabHost.newTabSpec(Constants.TAB_TEXT).setIndicator("text").setContent(R.id.submit_text_view));
    mTabHost.setOnTabChangedListener(new OnTabChangeListener() {
        public void onTabChanged(String tabId) {
            // Copy everything (except url and text) from old tab to new tab
            final EditText submitLinkTitle = (EditText) findViewById(R.id.submit_link_title);
            final EditText submitLinkReddit = (EditText) findViewById(R.id.submit_link_reddit);
            final EditText submitTextTitle = (EditText) findViewById(R.id.submit_text_title);
            final EditText submitTextReddit = (EditText) findViewById(R.id.submit_text_reddit);
            if (Constants.TAB_LINK.equals(tabId)) {
                submitLinkTitle.setText(submitTextTitle.getText());
                submitLinkReddit.setText(submitTextReddit.getText());
            } else {
                submitTextTitle.setText(submitLinkTitle.getText());
                submitTextReddit.setText(submitLinkReddit.getText());
            }
        }
    });
    mTabHost.setCurrentTab(0);

    if (mSettings.isLoggedIn()) {
        start();
    } else {
        showDialog(Constants.DIALOG_LOGIN);
    }
}

From source file:com.easy.facebook.android.facebook.FBLoginManager.java

public void logout(Facebook facebook) throws EasyFacebookError {
    SharedPreferences preferences = this.getActivity().getSharedPreferences(appID, 0);
    android.content.SharedPreferences.Editor editor = preferences.edit();
    editor.putString("accessToken", "");
    editor.putString("uid", "");
    editor.clear();//from  w  ww.  jav  a  2 s . co  m
    editor.commit();

    CookieSyncManager.createInstance(activity);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.removeAllCookie();

    Bundle params = new Bundle();
    params.putString("format", "json");
    params.putString("access_token", facebook.getAccessToken());
    params.putString("method", "auth.expireSession");
    String jsonResponse = "";

    try {
        jsonResponse = Util.openUrl("https://api.facebook.com/restserver.php", "GET", params);

        if (!jsonResponse.equals("true")) {

            JSONObject objectJSONErrorCheck = new JSONObject(jsonResponse);

            if (!objectJSONErrorCheck.isNull("error_msg")) {
                throw new EasyFacebookError(jsonResponse);

            }
        }
    } catch (MalformedURLException e) {

        throw new EasyFacebookError(e.toString(), "MalformedURLException");
    } catch (IOException e) {

        throw new EasyFacebookError(e.toString(), "IOException");
    } catch (JSONException e) {

        throw new EasyFacebookError(e.toString(), "JSONException");
    }

    ((LoginListener) activity).logoutSuccess();

}

From source file:com.hhunj.hhudata.SearchBookContentsActivity.java

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

    // Make sure that expired cookies are removed on launch.
    CookieSyncManager.createInstance(this);
    CookieManager.getInstance().removeExpiredCookie();

    Intent intent = getIntent();//www. j  a v  a 2s  .  co m
    if (intent == null || (!intent.getAction().equals(Intents.SearchBookContents.ACTION))) {
        finish();
        return;
    }

    //pageid,pagenumber
    //ISBN  ---stationid,
    isbn = intent.getStringExtra(Intents.SearchBookContents.ISBN);//stationid
    if (isbn.startsWith("http://google.com/books?id=")) {
        setTitle(getString(R.string.sbc_name));
    } else {
        setTitle(getString(R.string.sbc_name) + ": ISBN " + isbn);
    }

    setContentView(R.layout.search_book_contents);
    queryTextView = (EditText) findViewById(R.id.query_text_view);

    String initialQuery = intent.getStringExtra(Intents.SearchBookContents.QUERY);
    if (initialQuery != null && initialQuery.length() > 0) {
        // Populate the search box but don't trigger the search
        queryTextView.setText(initialQuery);
    }
    queryTextView.setOnKeyListener(keyListener);

    queryButton = (Button) findViewById(R.id.query_button);
    queryButton.setOnClickListener(buttonListener);

    resultListView = (ListView) findViewById(R.id.result_list_view);
    LayoutInflater factory = LayoutInflater.from(this);
    headerView = (TextView) factory.inflate(R.layout.search_book_contents_header, resultListView, false);
    resultListView.addHeaderView(headerView);
}

From source file:com.nguyenmp.gauchodroid.login.LoginFragment.java

public static void setCookies(Context context, CookieStore cookies) {
    PersistentCookieStore store = new PersistentCookieStore(context);
    store.clear();//from   w w  w . j a  v a 2 s. co  m

    CookieSyncManager.createInstance(context);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.removeAllCookie();
    cookieManager.setAcceptCookie(true);

    if (cookies != null) {
        for (Cookie cookie : cookies.getCookies()) {
            store.addCookie(cookie);
            cookieManager.setCookie(cookie.getDomain(), cookie.getName() + "=" + cookie.getValue());
        }
    }

    CookieSyncManager.getInstance().sync();
}

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

@SuppressLint("SetJavaScriptEnabled")
@Override/*from   ww w  . j a v a  2s .  c  om*/
public void onCreate(Bundle savedInstanceState) {
    Log_OC.v(TAG, "onCreate, savedInstanceState is " + savedInstanceState);
    super.onCreate(savedInstanceState);

    setRetainInstance(true);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        CookieSyncManager.createInstance(getActivity().getApplicationContext());
    }

    mInitialUrl = getArguments().getString(ARG_INITIAL_URL);
    mTargetUrls = getArguments().getStringArrayList(ARG_TARGET_URLS);

    setStyle(DialogFragment.STYLE_NO_TITLE, 0);
}

From source file:com.microsoft.aad.adal.AuthenticationActivity.java

@SuppressLint("SetJavaScriptEnabled")
@Override//from  w  ww  .j  av a 2s  .  c  o m
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(
            this.getResources().getIdentifier("activity_authentication", "layout", this.getPackageName()));
    CookieSyncManager.createInstance(getApplicationContext());
    CookieSyncManager.getInstance().sync();
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);

    // Get the message from the intent
    mAuthRequest = getAuthenticationRequestFromIntent(getIntent());
    if (mAuthRequest == null) {
        Log.d(TAG, "Request item is null, so it returns to caller");
        Intent resultIntent = new Intent();
        resultIntent.putExtra(AuthenticationConstants.Browser.RESPONSE_ERROR_CODE,
                AuthenticationConstants.Browser.WEBVIEW_INVALID_REQUEST);
        resultIntent.putExtra(AuthenticationConstants.Browser.RESPONSE_ERROR_MESSAGE,
                "Intent does not have request details");
        returnToCaller(AuthenticationConstants.UIResponse.BROWSER_CODE_ERROR, resultIntent);
        return;
    }

    if (mAuthRequest.getAuthority() == null || mAuthRequest.getAuthority().isEmpty()) {
        returnError(ADALError.ARGUMENT_EXCEPTION, AuthenticationConstants.Broker.ACCOUNT_AUTHORITY);
        return;
    }

    if (mAuthRequest.getResource() == null || mAuthRequest.getResource().isEmpty()) {
        returnError(ADALError.ARGUMENT_EXCEPTION, AuthenticationConstants.Broker.ACCOUNT_RESOURCE);
        return;
    }

    if (mAuthRequest.getClientId() == null || mAuthRequest.getClientId().isEmpty()) {
        returnError(ADALError.ARGUMENT_EXCEPTION, AuthenticationConstants.Broker.ACCOUNT_CLIENTID_KEY);
        return;
    }

    if (mAuthRequest.getRedirectUri() == null || mAuthRequest.getRedirectUri().isEmpty()) {
        returnError(ADALError.ARGUMENT_EXCEPTION, AuthenticationConstants.Broker.ACCOUNT_REDIRECT);
        return;
    }

    mRedirectUrl = mAuthRequest.getRedirectUri();
    Logger.v(TAG, "OnCreate redirectUrl:" + mRedirectUrl);
    // Create the Web View to show the page
    mWebView = (WebView) findViewById(
            this.getResources().getIdentifier("webView1", "id", this.getPackageName()));
    Logger.v(TAG, "User agent:" + mWebView.getSettings().getUserAgentString());
    mStartUrl = "about:blank";

    try {
        Oauth2 oauth = new Oauth2(mAuthRequest);
        mStartUrl = oauth.getCodeRequestUrl();
        mQueryParameters = oauth.getAuthorizationEndpointQueryParameters();
    } catch (UnsupportedEncodingException e) {
        Log.d(TAG, e.getMessage());
        Intent resultIntent = new Intent();
        resultIntent.putExtra(AuthenticationConstants.Browser.RESPONSE_REQUEST_INFO, mAuthRequest);
        returnToCaller(AuthenticationConstants.UIResponse.BROWSER_CODE_ERROR, resultIntent);
        return;
    }

    // Create the broadcast receiver for cancel
    Logger.v(TAG, "Init broadcastReceiver with requestId:" + mAuthRequest.getRequestId() + " "
            + mAuthRequest.getLogInfo());
    mReceiver = new ActivityBroadcastReceiver();
    mReceiver.mWaitingRequestId = mAuthRequest.getRequestId();
    LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,
            new IntentFilter(AuthenticationConstants.Browser.ACTION_CANCEL));

    String userAgent = mWebView.getSettings().getUserAgentString();
    mWebView.getSettings()
            .setUserAgentString(userAgent + AuthenticationConstants.Broker.CLIENT_TLS_NOT_SUPPORTED);
    userAgent = mWebView.getSettings().getUserAgentString();
    Logger.v(TAG, "UserAgent:" + userAgent);

    if (isBrokerRequest(getIntent())) {
        // This activity is started from calling app and running in
        // Authenticator's process
        mCallingPackage = getCallingPackage();
        Logger.i(TAG, "It is a broker request for package:" + mCallingPackage, "");

        if (mCallingPackage == null) {
            Logger.v(TAG, "startActivityForResult is not used to call this activity");
            Intent resultIntent = new Intent();
            resultIntent.putExtra(AuthenticationConstants.Browser.RESPONSE_ERROR_CODE,
                    AuthenticationConstants.Browser.WEBVIEW_INVALID_REQUEST);
            resultIntent.putExtra(AuthenticationConstants.Browser.RESPONSE_ERROR_MESSAGE,
                    "startActivityForResult is not used to call this activity");
            returnToCaller(AuthenticationConstants.UIResponse.BROWSER_CODE_ERROR, resultIntent);
            return;
        }

        mAccountAuthenticatorResponse = getIntent()
                .getParcelableExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);
        if (mAccountAuthenticatorResponse != null) {
            mAccountAuthenticatorResponse.onRequestContinued();
        }
        PackageHelper info = new PackageHelper(AuthenticationActivity.this);
        mCallingPackage = getCallingPackage();
        mCallingUID = info.getUIDForPackage(mCallingPackage);
        String signatureDigest = info.getCurrentSignatureForPackage(mCallingPackage);
        mStartUrl = getBrokerStartUrl(mStartUrl, mCallingPackage, signatureDigest);

        if (!isCallerBrokerInstaller()) {
            Logger.v(TAG, "Caller needs to be verified using special redirectUri");
            mRedirectUrl = PackageHelper.getBrokerRedirectUrl(mCallingPackage, signatureDigest);
        }
        Logger.v(TAG,
                "OnCreate redirectUrl:" + mRedirectUrl + " startUrl:" + mStartUrl + " calling package:"
                        + mCallingPackage + " signatureDigest:" + signatureDigest + " current Context Package: "
                        + getPackageName());
    }
    mRegisterReceiver = false;
    final String postUrl = mStartUrl;
    Logger.i(TAG, "OnCreate startUrl:" + mStartUrl + " calling package:" + mCallingPackage, " device:"
            + android.os.Build.VERSION.RELEASE + " " + android.os.Build.MANUFACTURER + android.os.Build.MODEL);

    setupWebView(mRedirectUrl, mQueryParameters, mAuthRequest);

    if (savedInstanceState == null) {
        mWebView.post(new Runnable() {
            @Override
            public void run() {
                // load blank first to avoid error for not loading webview
                mWebView.loadUrl("about:blank");
                mWebView.loadUrl(postUrl);
            }
        });
    } else {
        Logger.v(TAG, "Reuse webview");
    }
}

From source file:com.facebook.login.WebViewLoginMethodHandler.java

void onWebDialogComplete(LoginClient.Request request, Bundle values, FacebookException error) {
    LoginClient.Result outcome;//from  w  ww . j  a  v  a 2  s  . com
    if (values != null) {
        // Actual e2e we got from the dialog should be used for logging.
        if (values.containsKey(ServerProtocol.DIALOG_PARAM_E2E)) {
            e2e = values.getString(ServerProtocol.DIALOG_PARAM_E2E);
        }

        try {
            AccessToken token = createAccessTokenFromWebBundle(request.getPermissions(), values,
                    AccessTokenSource.WEB_VIEW, request.getApplicationId());
            outcome = LoginClient.Result.createTokenResult(loginClient.getPendingRequest(), token);

            // Ensure any cookies set by the dialog are saved
            // This is to work around a bug where CookieManager may fail to instantiate if
            // CookieSyncManager has never been created.
            CookieSyncManager syncManager = CookieSyncManager.createInstance(loginClient.getActivity());
            syncManager.sync();
            saveCookieToken(token.getToken());
        } catch (FacebookException ex) {
            outcome = LoginClient.Result.createErrorResult(loginClient.getPendingRequest(), null,
                    ex.getMessage());
        }
    } else {
        if (error instanceof FacebookOperationCanceledException) {
            outcome = LoginClient.Result.createCancelResult(loginClient.getPendingRequest(),
                    "User canceled log in.");
        } else {
            // Something went wrong, don't log a completion event since it will skew timing
            // results.
            e2e = null;

            String errorCode = null;
            String errorMessage = error.getMessage();
            if (error instanceof FacebookServiceException) {
                FacebookRequestError requestError = ((FacebookServiceException) error).getRequestError();
                errorCode = String.format(Locale.ROOT, "%d", requestError.getErrorCode());
                errorMessage = requestError.toString();
            }
            outcome = LoginClient.Result.createErrorResult(loginClient.getPendingRequest(), null, errorMessage,
                    errorCode);
        }
    }

    if (!Utility.isNullOrEmpty(e2e)) {
        logWebLoginCompleted(e2e);
    }

    loginClient.completeAndValidate(outcome);
}

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;//from   w ww .  j  a  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:no.ntnu.idi.socialhitchhiking.facebook.FBConnectionActivity.java

/**
 * Initializes the Facebook user./*w  w  w. ja va2 s.c om*/
 * 
 * @param msg - A Message handled by the handler, consists of a {@link User}
 */
private void initiateUser(Message msg) {
    user = (User) msg.obj;
    user.setPicture(getPictureByteArray(user.getID()));
    getApp().setUser(user);
    //CookieSyncManager syncManager = 
    CookieSyncManager.createInstance(this);
    //syncManager.sync();
    main.onResult();
}