Example usage for android.accounts AccountManager getUserData

List of usage examples for android.accounts AccountManager getUserData

Introduction

In this page you can find the example usage for android.accounts AccountManager getUserData.

Prototype

public String getUserData(final Account account, final String key) 

Source Link

Document

Gets the user data named by "key" associated with the account.

Usage

From source file:org.klnusbaum.udj.PlaylistLoader.java

private PlaylistResult attemptLoad(boolean attemptReauth) {
    AccountManager am = AccountManager.get(getContext());
    String authToken = "";
    try {/*  www .j  a va2s .  c  om*/
        authToken = am.blockingGetAuthToken(account, "", true);
    } catch (IOException e) {
        //TODO this might actually be an auth error
        return new PlaylistResult(null, PlaylistLoadError.AUTHENTICATION_ERROR);
    } catch (AuthenticatorException e) {
        return new PlaylistResult(null, PlaylistLoadError.AUTHENTICATION_ERROR);
    } catch (OperationCanceledException e) {
        return new PlaylistResult(null, PlaylistLoadError.AUTHENTICATION_ERROR);
    }

    try {
        String playerId = am.getUserData(account, Constants.LAST_PLAYER_ID_DATA);
        JSONObject serverResult = ServerConnection.getActivePlaylist(playerId, authToken);
        List<ActivePlaylistEntry> toReturn = RESTProcessor.processActivePlaylist(serverResult, am, account,
                context);
        return new PlaylistResult(toReturn);
    } catch (JSONException e) {
        return new PlaylistResult(null, PlaylistLoadError.SERVER_ERROR);
    } catch (ParseException e) {
        return new PlaylistResult(null, PlaylistLoadError.SERVER_ERROR);
    } catch (IOException e) {
        return new PlaylistResult(null, PlaylistLoadError.SERVER_ERROR);
    } catch (AuthenticationException e) {
        if (attemptReauth) {
            Log.d(TAG, "soft auth failure");
            am.invalidateAuthToken(Constants.ACCOUNT_TYPE, authToken);
            return attemptLoad(false);
        } else {
            Log.d(TAG, "hard auth failure");
            return new PlaylistResult(null, PlaylistLoadError.AUTHENTICATION_ERROR);
        }
    } catch (PlayerInactiveException e) {
        return new PlaylistResult(null, PlaylistLoadError.PLAYER_INACTIVE_ERROR);
    } catch (NoLongerInPlayerException e) {
        return new PlaylistResult(null, PlaylistLoadError.NO_LONGER_IN_PLAYER_ERROR);
    } catch (KickedException e) {
        return new PlaylistResult(null, PlaylistLoadError.KICKED_ERROR);
    }
}

From source file:org.klnusbaum.udj.MusicSearchLoader.java

private MusicSearchResult attemptSearch(boolean attemptReauth) {
    AccountManager am = AccountManager.get(getContext());
    String authToken = "";
    try {//from   ww  w.  ja v  a 2s . c o  m
        authToken = am.blockingGetAuthToken(account, "", true);
    } catch (IOException e) {
        //TODO this might actually be an auth error
        return new MusicSearchResult(null, MusicSearchError.AUTHENTICATION_ERROR);
    } catch (AuthenticatorException e) {
        return new MusicSearchResult(null, MusicSearchError.AUTHENTICATION_ERROR);
    } catch (OperationCanceledException e) {
        return new MusicSearchResult(null, MusicSearchError.AUTHENTICATION_ERROR);
    }

    try {
        String playerId = am.getUserData(account, Constants.LAST_PLAYER_ID_DATA);
        return doSearch(playerId, authToken);
    } catch (JSONException e) {
        return new MusicSearchResult(null, MusicSearchError.SERVER_ERROR);
    } catch (ParseException e) {
        return new MusicSearchResult(null, MusicSearchError.SERVER_ERROR);
    } catch (IOException e) {
        return new MusicSearchResult(null, MusicSearchError.SERVER_ERROR);
    } catch (AuthenticationException e) {
        if (attemptReauth) {
            Log.d(TAG, "soft auth failure");
            am.invalidateAuthToken(Constants.ACCOUNT_TYPE, authToken);
            return attemptSearch(false);
        } else {
            Log.d(TAG, "hard auth failure");
            return new MusicSearchResult(null, MusicSearchError.AUTHENTICATION_ERROR);
        }
    } catch (PlayerInactiveException e) {
        return new MusicSearchResult(null, MusicSearchError.PLAYER_INACTIVE_ERROR);
    } catch (NoLongerInPlayerException e) {
        return new MusicSearchResult(null, MusicSearchError.NO_LONGER_IN_PLAYER_ERROR);
    } catch (KickedException e) {
        return new MusicSearchResult(null, MusicSearchError.KICKED_ERROR);
    }
}

From source file:com.ntsync.android.sync.syncadapter.SyncAdapter.java

private void notifyUserPhotoNotSynced(String accountName) {
    Account account = new Account(accountName, Constants.ACCOUNT_TYPE);
    AccountManager acm = AccountManager.get(mContext);
    String synced = acm.getUserData(account, NOTIF_SHOWN_PHOTO_SYNCED);
    if (synced == null) {
        Intent shopIntent = new Intent(mContext, ShopActivity.class);
        shopIntent.putExtra(ShopActivity.PARM_ACCOUNT_NAME, accountName);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(mContext);
        stackBuilder.addParentStack(ShopActivity.class);
        stackBuilder.addNextIntent(shopIntent);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext)
                .setSmallIcon(Constants.NOTIF_ICON)
                .setContentTitle(getText(R.string.notif_photonotsynced_title)).setContentText(accountName)
                .setAutoCancel(true)//from w ww. j a v  a 2s  . c o  m
                .setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT))
                .setOnlyAlertOnce(true);
        NotificationManager mNotificationManager = (NotificationManager) mContext
                .getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(Constants.NOTIF_PHOTO_NOT_SYNCED, mBuilder.build());
        acm.setUserData(account, NOTIF_SHOWN_PHOTO_SYNCED, String.valueOf(System.currentTimeMillis()));
    }
}

From source file:org.totschnig.myexpenses.sync.SyncAdapter.java

private String getUserDataWithDefault(AccountManager accountManager, Account account, String key,
        String defaultValue) {//ww w .  j  a  va2  s.  c  o  m
    String value = accountManager.getUserData(account, key);
    return value == null ? defaultValue : value;
}

From source file:com.ntsync.android.sync.syncadapter.SyncAdapter.java

private void notifyUserConctactNotSynced(int maxCount, int totalLocalContacts, String accountName) {
    AccountManager acm = AccountManager.get(mContext);
    Account account = new Account(accountName, Constants.ACCOUNT_TYPE);
    String lastTimeShown = acm.getUserData(account, NOTIF_SHOWN_CONTACTS_SYNCED);
    Long lastTime;//ww w.j a v  a2  s.c om
    try {
        lastTime = lastTimeShown != null ? Long.parseLong(lastTimeShown) : null;
    } catch (NumberFormatException ex) {
        LogHelper.logWCause(TAG,
                "Invalid Config-Settings:" + NOTIF_SHOWN_CONTACTS_SYNCED + " Value:" + lastTimeShown, ex);
        lastTime = null;
    }

    if (lastTime == null || System.currentTimeMillis() > lastTime.longValue() + NOTIF_WAIT_TIME) {
        // Create Shop-Intent
        Intent shopIntent = new Intent(mContext, ShopActivity.class);
        shopIntent.putExtra(ShopActivity.PARM_ACCOUNT_NAME, account.name);
        // Adds the back stack
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(mContext);
        stackBuilder.addParentStack(ShopActivity.class);
        stackBuilder.addNextIntent(shopIntent);

        // Create Notification
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext)
                .setSmallIcon(Constants.NOTIF_ICON)
                .setContentTitle(String.format(getText(R.string.notif_contactnotsynced_title), maxCount,
                        totalLocalContacts))
                .setContentText(String.format(getText(R.string.notif_contactnotsynced_content), account.name))
                .setAutoCancel(true).setOnlyAlertOnce(true)
                .setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT));
        NotificationManager mNotificationManager = (NotificationManager) mContext
                .getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(Constants.NOTIF_CONTACTS_NOT_SYNCED, mBuilder.build());
        acm.setUserData(account, NOTIF_SHOWN_CONTACTS_SYNCED, String.valueOf(System.currentTimeMillis()));
    }
}

From source file:com.sintef_energy.ubisolar.activities.DrawerActivity.java

/**
 * Handles the startup authentication./*from  ww  w .j av  a 2 s  . c o m*/
 *
 * Authenticates to facebook. If no authentication data is present, then
 * nothing happens. The user must explicitly say that he wants to login.
 *
 * @param savedInstanceState Saved instance data
 */
private void startFacebookLogin(Bundle savedInstanceState) {
    mAccount = getAccount(getApplicationContext(), ACCOUNT_TYPE);

    // start Facebook Login
    // This will _only_ log in if the user is logged in from before.
    // To log in, the user must choose so himself from the menu.
    Session session = Session.getActiveSession();

    // We don't have a session
    if (session == null) {
        // We have session data
        if (savedInstanceState != null) {
            session = Session.restoreSession(this, null, mFacebookSessionStatusCallback, savedInstanceState);
        }
        if (session == null) {
            session = new Session(this);
        }

        // Try to open the session
        Session.setActiveSession(session);

        // Do we have cached tokens
        if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
            session.openForRead(new Session.OpenRequest(this).setCallback(mFacebookSessionStatusCallback));
        }
        // Use token from AccountManager
        else {
            if (mAccount == null) {
                Log.v(TAG, "startAppLogin account does not exist. Aborting");
                return;
            }

            AccountManager accountManager = (AccountManager) getApplicationContext()
                    .getSystemService(ACCOUNT_SERVICE);
            String token = accountManager.getUserData(mAccount, Global.DATA_AUTH_TOKEN);
            String exprDate = accountManager.getUserData(mAccount, Global.DATA_EXPIRATION_DATE);

            if (token == null) {
                Log.v(TAG, "No account to login to.");
                return;
            }

            migrateFbTokenToSession(token, new Date(Long.valueOf(exprDate)));
        }
    } else if (session.isOpened()) {
        session.addCallback(mFacebookSessionStatusCallback);
        updatePreferenceWithFacebookData(session);
        changeNavdrawerSessionsView(true);
        Log.v(TAG, "startFacebookLogin: got active session.");
    } else
        Log.v(TAG, "startFacebookLogin: No session.");
}

From source file:com.sintef_energy.ubisolar.activities.DrawerActivity.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);

    if (requestCode == LOGIN_CALL_ID) {
        if (resultCode == Activity.RESULT_OK) {
            Log.v(TAG, "Login was successful. Starting to attain session data.");

            startFacebookLogin(null);// w w  w . j av  a 2s.  co  m

            // Find the account
            Account[] accounts = getAccounts(getApplicationContext(), ACCOUNT_TYPE);
            for (Account account : accounts) {
                if (account.name.equals(data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME))) {
                    mAccount = account;
                    break;
                }
            }

            if (mAccount == null) {
                Log.e(TAG, "Account creation somehow failed to make an account.");
                return;
            }

            /* The same as ticking allow sync */
            ContentResolver.setSyncAutomatically(mAccount, AUTHORITY_PROVIDER, true);

            /* Request a sync operation */
            Bundle bundle = new Bundle();
            bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); //Do sync regardless of settings
            bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); //Force sync immediately
            ContentResolver.requestSync(mAccount, AUTHORITY_PROVIDER, bundle);

            /* Update all -1 users to the current user id. */
            AccountManager accountManager = (AccountManager) getApplicationContext()
                    .getSystemService(ACCOUNT_SERVICE);

            String facebookUID = accountManager.getUserData(mAccount, Global.DATA_FB_UID);

            ContentValues values = new ContentValues();
            values.put(DeviceModel.DeviceEntry.COLUMN_USER_ID, facebookUID);
            values.put(DeviceModel.DeviceEntry.COLUMN_LAST_UPDATED, System.currentTimeMillis() / 1000L);

            getContentResolver().update(EnergyContract.Devices.CONTENT_URI, values,
                    EnergyContract.Devices.COLUMN_USER_ID + "=?", new String[] { "-1" });

            //Publish a post saying you started using Wattitude
            RequestManager.getInstance().doFriendRequest().createWallPost(
                    new NewsFeedPost(0, Long.valueOf(facebookUID), 1, System.currentTimeMillis() / 1000), null);
        } else {
            Log.v(TAG, "Login failed");
        }
    }
}

From source file:com.digitalarx.android.files.services.FileUploader.java

/**
 * Entry point to add one or several files to the queue of uploads.
 * //from   w  ww  .j  av  a  2 s.  c  o m
 * New uploads are added calling to startService(), resulting in a call to
 * this method. This ensures the service will keep on working although the
 * caller activity goes away.
 */
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (!intent.hasExtra(KEY_ACCOUNT) || !intent.hasExtra(KEY_UPLOAD_TYPE)
            || !(intent.hasExtra(KEY_LOCAL_FILE) || intent.hasExtra(KEY_FILE))) {
        Log_OC.e(TAG, "Not enough information provided in intent");
        return Service.START_NOT_STICKY;
    }
    int uploadType = intent.getIntExtra(KEY_UPLOAD_TYPE, -1);
    if (uploadType == -1) {
        Log_OC.e(TAG, "Incorrect upload type provided");
        return Service.START_NOT_STICKY;
    }
    Account account = intent.getParcelableExtra(KEY_ACCOUNT);

    String[] localPaths = null, remotePaths = null, mimeTypes = null;
    OCFile[] files = null;
    if (uploadType == UPLOAD_SINGLE_FILE) {

        if (intent.hasExtra(KEY_FILE)) {
            files = new OCFile[] { intent.getParcelableExtra(KEY_FILE) };

        } else {
            localPaths = new String[] { intent.getStringExtra(KEY_LOCAL_FILE) };
            remotePaths = new String[] { intent.getStringExtra(KEY_REMOTE_FILE) };
            mimeTypes = new String[] { intent.getStringExtra(KEY_MIME_TYPE) };
        }

    } else { // mUploadType == UPLOAD_MULTIPLE_FILES

        if (intent.hasExtra(KEY_FILE)) {
            files = (OCFile[]) intent.getParcelableArrayExtra(KEY_FILE); // TODO
                                                                         // will
                                                                         // this
                                                                         // casting
                                                                         // work
                                                                         // fine?

        } else {
            localPaths = intent.getStringArrayExtra(KEY_LOCAL_FILE);
            remotePaths = intent.getStringArrayExtra(KEY_REMOTE_FILE);
            mimeTypes = intent.getStringArrayExtra(KEY_MIME_TYPE);
        }
    }

    FileDataStorageManager storageManager = new FileDataStorageManager(account, getContentResolver());

    boolean forceOverwrite = intent.getBooleanExtra(KEY_FORCE_OVERWRITE, false);
    boolean isInstant = intent.getBooleanExtra(KEY_INSTANT_UPLOAD, false);
    int localAction = intent.getIntExtra(KEY_LOCAL_BEHAVIOUR, LOCAL_BEHAVIOUR_COPY);

    if (intent.hasExtra(KEY_FILE) && files == null) {
        Log_OC.e(TAG, "Incorrect array for OCFiles provided in upload intent");
        return Service.START_NOT_STICKY;

    } else if (!intent.hasExtra(KEY_FILE)) {
        if (localPaths == null) {
            Log_OC.e(TAG, "Incorrect array for local paths provided in upload intent");
            return Service.START_NOT_STICKY;
        }
        if (remotePaths == null) {
            Log_OC.e(TAG, "Incorrect array for remote paths provided in upload intent");
            return Service.START_NOT_STICKY;
        }
        if (localPaths.length != remotePaths.length) {
            Log_OC.e(TAG, "Different number of remote paths and local paths!");
            return Service.START_NOT_STICKY;
        }

        files = new OCFile[localPaths.length];
        for (int i = 0; i < localPaths.length; i++) {
            files[i] = obtainNewOCFileToUpload(remotePaths[i], localPaths[i],
                    ((mimeTypes != null) ? mimeTypes[i] : (String) null), storageManager);
            if (files[i] == null) {
                // TODO @andomaex add failure Notification
                return Service.START_NOT_STICKY;
            }
        }
    }

    AccountManager aMgr = AccountManager.get(this);
    String version = aMgr.getUserData(account, Constants.KEY_OC_VERSION);
    OwnCloudVersion ocv = new OwnCloudVersion(version);

    boolean chunked = FileUploader.chunkedUploadIsSupported(ocv);
    AbstractList<String> requestedUploads = new Vector<String>();
    String uploadKey = null;
    UploadFileOperation newUpload = null;
    try {
        for (int i = 0; i < files.length; i++) {
            uploadKey = buildRemoteName(account, files[i].getRemotePath());
            newUpload = new UploadFileOperation(account, files[i], chunked, isInstant, forceOverwrite,
                    localAction, getApplicationContext());
            if (isInstant) {
                newUpload.setRemoteFolderToBeCreated();
            }
            mPendingUploads.putIfAbsent(uploadKey, newUpload); // Grants that the file only upload once time

            newUpload.addDatatransferProgressListener(this);
            newUpload.addDatatransferProgressListener((FileUploaderBinder) mBinder);
            requestedUploads.add(uploadKey);
        }

    } catch (IllegalArgumentException e) {
        Log_OC.e(TAG, "Not enough information provided in intent: " + e.getMessage());
        return START_NOT_STICKY;

    } catch (IllegalStateException e) {
        Log_OC.e(TAG, "Bad information provided in intent: " + e.getMessage());
        return START_NOT_STICKY;

    } catch (Exception e) {
        Log_OC.e(TAG, "Unexpected exception while processing upload intent", e);
        return START_NOT_STICKY;

    }

    if (requestedUploads.size() > 0) {
        Message msg = mServiceHandler.obtainMessage();
        msg.arg1 = startId;
        msg.obj = requestedUploads;
        mServiceHandler.sendMessage(msg);
    }
    Log_OC.i(TAG, "mPendingUploads size:" + mPendingUploads.size());
    return Service.START_NOT_STICKY;
}

From source file:com.nextgis.maplibui.SelectNGWResourceDialog.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == ADDACCOUNT_CODE) {
        if (resultCode != Activity.RESULT_CANCELED) {
            //search new account and add it
            final AccountManager accountManager = AccountManager.get(getActivity());
            Connections connections = mListAdapter.getConnections();
            for (Account account : accountManager.getAccountsByType(NGW_ACCOUNT_TYPE)) {
                boolean find = false;
                for (int i = 0; i < connections.getChildrenCount(); i++) {
                    Connection connection = (Connection) connections.getChild(i);
                    if (null != connection && connection.getName().equals(account.name)) {
                        find = true;//from  w ww .  ja va2  s.co  m
                        break;
                    }
                }

                if (!find) {
                    String url = accountManager.getUserData(account, "url");
                    String password = accountManager.getPassword(account);
                    String login = accountManager.getUserData(account, "login");
                    connections.add(new Connection(account.name, login, password, url));
                    mListAdapter.notifyDataSetChanged();
                    break;
                }
            }
        }
    } else
        super.onActivityResult(requestCode, resultCode, data);
}