Example usage for com.google.api.client.googleapis.extensions.android.gms.auth GoogleAccountCredential getSelectedAccountName

List of usage examples for com.google.api.client.googleapis.extensions.android.gms.auth GoogleAccountCredential getSelectedAccountName

Introduction

In this page you can find the example usage for com.google.api.client.googleapis.extensions.android.gms.auth GoogleAccountCredential getSelectedAccountName.

Prototype

public final String getSelectedAccountName() 

Source Link

Document

Returns the selected Google account name (e-mail address), for example "johndoe@gmail.com" , or null for none.

Usage

From source file:ch.hesso.master.sweetcity.utils.PictureUtils.java

License:Apache License

public static Key uploadPicture(Bitmap picture, GoogleAccountCredential googleCredential) {
    if (picture == null)
        return null;

    try {//  w  ww .j  a  v a2s. c o m
        ClientConfiguration clientConfig = new ClientConfiguration();
        clientConfig.setProtocol(Protocol.HTTP);
        AmazonS3 s3Connection = new AmazonS3Client(AWS_CREDENTIALS, clientConfig);
        s3Connection.setEndpoint(ConstantsAWS.S3_END_POINT);

        ObjectMetadata pictureMetadata = new ObjectMetadata();

        String key = String.format(ConstantsAWS.S3_PICTURE_NAME_FORMAT,
                googleCredential.getSelectedAccountName(), Constants.DATE_FORMAT_IMAGE.format(new Date()));

        s3Connection.putObject(ConstantsAWS.S3_BUCKET_NAME, key, ImageUtils.bitmapToInputStream(picture),
                pictureMetadata);

        return new Key(key);
    } catch (Exception e) {
        Log.d(Constants.PROJECT_NAME, e.toString());
    }

    return null;
}

From source file:com.battlelancer.seriesguide.backend.HexagonTools.java

License:Apache License

/**
 * Creates and returns a new instance for this hexagon service or null if not signed in.
 */// ww  w.ja  v a 2  s  .c o m
@Nullable
public static synchronized Account buildAccountService(Context context) {
    GoogleAccountCredential credential = getAccountCredential(context);
    if (credential.getSelectedAccountName() == null) {
        return null;
    }
    Account.Builder builder = new Account.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential);
    return CloudEndpointUtils.updateBuilder(builder).build();
}

From source file:com.battlelancer.seriesguide.backend.HexagonTools.java

License:Apache License

/**
 * Returns the instance for this hexagon service or null if not signed in.
 *//*from ww  w  . j a  va2s .  c  o  m*/
@Nullable
public static synchronized Shows getShowsService(Context context) {
    GoogleAccountCredential credential = getAccountCredential(context);
    if (credential.getSelectedAccountName() == null) {
        return null;
    }
    if (sShowsService == null) {
        Shows.Builder builder = new Shows.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential);
        sShowsService = CloudEndpointUtils.updateBuilder(builder).build();
    }
    return sShowsService;
}

From source file:com.battlelancer.seriesguide.backend.HexagonTools.java

License:Apache License

/**
 * Returns the instance for this hexagon service or null if not signed in.
 *///from w  ww .  j  a v a  2s .  c  om
@Nullable
public static synchronized Episodes getEpisodesService(Context context) {
    GoogleAccountCredential credential = getAccountCredential(context);
    if (credential.getSelectedAccountName() == null) {
        return null;
    }
    if (sEpisodesService == null) {
        Episodes.Builder builder = new Episodes.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential);
        sEpisodesService = CloudEndpointUtils.updateBuilder(builder).build();
    }
    return sEpisodesService;
}

From source file:com.battlelancer.seriesguide.backend.HexagonTools.java

License:Apache License

/**
 * Returns the instance for this hexagon service or null if not signed in.
 *//*from  w  w  w.jav a 2 s  . c  o m*/
@Nullable
public static synchronized Movies getMoviesService(Context context) {
    GoogleAccountCredential credential = getAccountCredential(context);
    if (credential.getSelectedAccountName() == null) {
        return null;
    }
    if (sMoviesService == null) {
        Movies.Builder builder = new Movies.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential);
        sMoviesService = CloudEndpointUtils.updateBuilder(builder).build();
    }
    return sMoviesService;
}

From source file:com.battlelancer.seriesguide.backend.HexagonTools.java

License:Apache License

/**
 * Checks if the given Google account exists and can be accessed.
 *///from   w w  w .  j  a  v  a  2  s  .c o  m
public static boolean validateAccount(Context context, String accountName) {
    GoogleAccountCredential credential = GoogleAccountCredential.usingAudience(context.getApplicationContext(),
            HexagonSettings.AUDIENCE);
    // set account, credential tries to fetch Google account from Android AccountManager
    credential.setSelectedAccountName(accountName);

    if (credential.getSelectedAccountName() == null) {
        Timber.e("validateAccount: failed to get Google account from AccountManager.");
        return false;
    }

    return true;
}

From source file:com.google.cloud.genomics.android.CredentialActivity.java

License:Apache License

protected void checkCredential() {
    GoogleAccountCredential credential = getCredential(this);

    if (credential.getSelectedAccountName() == null) {
        startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
    } else if (!isDeviceOnline(this)) {
        Toast.makeText(this, "No network connection available, this app won't show any data.",
                Toast.LENGTH_SHORT).show();
    } else {/*from  www  .j  ava 2  s.c  o  m*/
        credentialAvailable = true;
        handleCredential();
    }
}

From source file:com.meiste.tempalarm.ui.CurrentTemp.java

License:Apache License

@Override
protected void onResume() {
    super.onResume();
    mSyncStatusObserver.onStatusChanged(0);

    if (checkPlayServices()) {
        final GoogleAccountCredential credential = AccountUtils.getCredential(this);
        if (credential.getSelectedAccountName() != null) {
            GCMHelper.registerIfNeeded(getApplicationContext(), AppConstants.GCM_SENDER_ID, this);
        } else {//from   w w  w .  j  ava 2  s .  com
            startActivityForResult(credential.newChooseAccountIntent(), ACCOUNT_PICKER_REQUEST);
        }

        // Watch for sync state changes
        final int mask = ContentResolver.SYNC_OBSERVER_TYPE_PENDING | ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE;
        mSyncObserverHandle = ContentResolver.addStatusChangeListener(mask, mSyncStatusObserver);
    }
}

From source file:edu.uvawise.iris.sync.SyncAdapter.java

License:Apache License

/**
 * Called by the Android system in response to a request to run the sync adapter. The work
 * required to read data from the network, parse it, and store it in the content provider is
 * done here. Extending AbstractThreadedSyncAdapter ensures that all methods within SyncAdapter
 * run on a background thread. For this reason, blocking I/O and other long-running tasks can be
 * run <em>in situ</em>, and you don't have to set up a separate thread for them.
 * .// www .j a v a  2s .co m
 * <p/>
 * <p>This is where we actually perform any work required to perform a sync.
 * {@link android.content.AbstractThreadedSyncAdapter} guarantees that this will be called on a non-UI thread,
 * so it is safe to peform blocking I/O here.
 * <p/>
 * <p>The syncResult argument allows you to pass information back to the method that triggered
 * the sync.
 */
@Override
public void onPerformSync(final Account account, Bundle extras, String authority,
        ContentProviderClient provider, SyncResult syncResult) {
    Log.i(TAG, ".");
    Log.i(TAG, "-------------------------------------------------------");
    Log.i(TAG, "Beginning synchronization for: " + account.name);
    Log.i(TAG, "-------------------------------------------------------");

    ArrayList<GmailAccount> accounts = GmailUtils.getGmailAccounts(context);

    if (accounts == null || accounts.isEmpty()) {
        Log.e(TAG, "Can't sync. No accounts.");
        return;
    }

    boolean loggedIn = false;
    for (GmailAccount gmailAccount : accounts) {
        if (gmailAccount.getUserID().equals(account.name)) {
            loggedIn = true;
            break;
        }
    }

    GoogleAccountCredential credential;
    if (loggedIn) {
        Log.d(TAG, "" + account.name);
        try {
            credential = GmailUtils.getGmailAccountCredential(context, account.name);
            if (credential == null) {
                Log.d(TAG, "Credential Null");
                return;
            }

            gmail = GmailUtils.getGmailService(credential);

            Log.d(TAG, "Sync Running for:" + credential.getSelectedAccountName());
            Log.d(TAG, "Cred Name:" + credential.getSelectedAccountName());

            try {
                if (canPartialSync(credential)) {
                    performPartialSync(credential);
                } else {
                    performFullSync(credential);
                }
            } catch (MessagingException | IOException e) {
                Log.e(TAG, "Error Syncing");
            }

        } catch (UserRecoverableAuthException e) {
            GmailUtils.permissionNotification(context, e.getIntent(), account.name);
        } catch (GoogleAuthException e) {
            Log.e(TAG, "GoogleAuthException", e);
        } catch (UserRecoverableAuthIOException e) {
            GmailUtils.permissionNotification(context, e.getIntent(), account.name);
        } catch (IOException e) {
            Log.e(TAG, "IOException", e);
            syncResult.databaseError = true;
        } finally {
            credential = null;
        }
        Log.i(TAG, "Synchronization complete for:" + account.name);
        Log.i(TAG, "-------------------------------------------------------");
        Log.i(TAG, ".");
    }

}

From source file:edu.uvawise.iris.sync.SyncAdapter.java

License:Apache License

/**
 * We have never synced or can't use the current history ID. We need to do a full sync with
 * the server.//from  w  ww . ja va  2s. c o m
 *
 * @param credential Google crediential to use to sync with.
 * @throws MessagingException
 * @throws IOException
 */
private void performFullSync(GoogleAccountCredential credential) throws MessagingException, IOException {
    Log.i(TAG, "Performing Full Sync");
    final ContentResolver contentResolver = context.getContentResolver();
    String userID = credential.getSelectedAccountName();

    contentResolver.delete(IrisContentProvider.MESSAGES_URI, IrisContentProvider.USER_ID + " = ?",
            new String[] { userID });

    Gmail.Users.Messages.List mailList = gmail.users().messages().list("me").setFields("messages(id,historyId)")
            .setQ("in:inbox !is:chat").setIncludeSpamTrash(false);
    ListMessagesResponse response = mailList.execute();

    ArrayList<ContentProviderOperation> batch = new ArrayList<>();

    if (response.getMessages() == null)
        return;
    BigInteger newHistID = null;
    BigInteger temp = null;
    for (Message msgID : response.getMessages()) {
        temp = addMessage(credential, msgID.getId(), batch);
        if (newHistID == null)
            newHistID = temp;
    }

    try {
        contentResolver.applyBatch(SyncUtils.SYNC_AUTH, batch);
        contentResolver.notifyChange(IrisContentProvider.MESSAGES_URI, // URI where data was modified
                null, // No local observer
                false);
        GmailUtils.setCurrentHistoryID(context, userID, newHistID);
    } catch (RemoteException | OperationApplicationException e) {
        Log.e(TAG, "Error updating database: " + e.toString());
    }
}