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:edu.uvawise.iris.sync.SyncAdapter.java

License:Apache License

/**
 * Determine if we can do a partial sync or not.
 *
 * @param credential The Google Credential to use to sync.
 * @return True if we can use partial sync. False otherwise.
 * @throws IOException//from   www.ja va2 s  .co m
 */
private boolean canPartialSync(GoogleAccountCredential credential) throws IOException {
    BigInteger histID = GmailUtils.getCurrentHistoryID(context, credential.getSelectedAccountName());
    if (histID == null)
        return false;
    try {
        ListHistoryResponse response = getHistoryResponse(credential, histID);
        if (response != null) {
            return true;
        }
    } catch (HttpResponseException e) {
        return false;
    }
    return false;
}

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

License:Apache License

/**
 * Perform a partial sync with the Gmail server.
 *
 * @param credential The Google Credential to sync with.
 * @throws MessagingException//from  w  w  w  .j  av a2 s.c  om
 * @throws IOException
 */
private void performPartialSync(GoogleAccountCredential credential) throws MessagingException, IOException {
    Log.i(TAG, "Performing Partial Sync");
    final ContentResolver contentResolver = context.getContentResolver();
    String userID = credential.getSelectedAccountName();
    BigInteger histID = GmailUtils.getCurrentHistoryID(context, userID);

    if (histID == null) {
        Log.e(TAG, "No history ID available. (Maybe invalid or haven't done a full sync)");
        return;
    }
    Log.i(TAG, "Using history ID: " + histID);
    ListHistoryResponse response = getHistoryResponse(credential, histID);
    if (response == null) {
        Log.e(TAG, "No history response.");
        return;
    }

    BigInteger newHistID = GmailUtils.getCurrentHistoryID(context, userID);
    ArrayList<ContentProviderOperation> batch = new ArrayList<>();
    if (response.getHistory() != null) {
        if (!response.getHistory().isEmpty()) {

            ArrayList<Message> addedMessages = new ArrayList<>();
            ArrayList<Message> deletedMessages = new ArrayList<>();

            List<History> histories = new ArrayList<History>();
            while (response.getHistory() != null) {
                histories.addAll(response.getHistory());
                newHistID = response.getHistoryId();
                if (response.getNextPageToken() != null) {
                    String pageToken = response.getNextPageToken();
                    response = getHistoryResponse(credential, histID, pageToken);
                } else {
                    break;
                }
            }

            for (History hist : histories) {
                if (hist.getLabelsAdded() != null) {
                    for (HistoryLabelAdded msgA : hist.getLabelsAdded()) {
                        addedMessages.add(msgA.getMessage());
                    }
                }
                if (hist.getLabelsRemoved() != null) {
                    for (HistoryLabelRemoved msgD : hist.getLabelsRemoved()) {
                        deletedMessages.add(msgD.getMessage());
                    }
                }
                if (hist.getMessagesAdded() != null) {
                    for (HistoryMessageAdded msgA : hist.getMessagesAdded()) {
                        addedMessages.add(msgA.getMessage());
                    }
                }
                if (hist.getMessagesDeleted() != null) {
                    for (HistoryMessageDeleted msgD : hist.getMessagesDeleted()) {
                        deletedMessages.add(msgD.getMessage());
                    }
                }
            }

            for (Message msgID : addedMessages) {
                addMessage(credential, msgID.getId(), batch);
            }

            for (Message msgID : deletedMessages) {
                deleteMessage(msgID.getId(), batch);
            }

            GmailUtils.setCurrentHistoryID(context, userID, newHistID);
            if (IrisVoiceService.isRunning() && newMessages != null && !newMessages.isEmpty()) {
                Log.d(TAG, "Putting new messages in the intent.");
                Intent serviceIntent = new Intent(context, IrisVoiceService.class);
                String[] stockArr = new String[newMessages.size()];
                String[] stockArr2 = new String[newMessageAccounts.size()];
                stockArr = newMessages.toArray(stockArr);
                serviceIntent.putExtra(IrisVoiceService.INTENT_DATA_MESSAGES_ADDED,
                        newMessages.toArray(stockArr));
                stockArr2 = newMessageAccounts.toArray(stockArr2);
                serviceIntent.putExtra(IrisVoiceService.INTENT_DATA_MESSAGE_ACCOUNTS,
                        newMessageAccounts.toArray(stockArr2));
                context.startService(serviceIntent);
                newMessages.clear();
                newMessageAccounts.clear();
            }
        }
    }

    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());
    }

}

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

License:Apache License

/**
 * Get the message with the specified ID from the Gmail server and add it to the database
 * batch operations.//from ww  w  . j ava 2  s  . c o m
 *
 * @param credential The Google Credential to sync with
 * @param msgID      The message ID to add.
 * @param batch      The array that is holding the database batch operations.
 * @return Returns the history ID of the message added.
 * @throws IOException
 * @throws MessagingException
 */
private BigInteger addMessage(GoogleAccountCredential credential, String msgID,
        ArrayList<ContentProviderOperation> batch) throws IOException, MessagingException {
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage mimeMessage;
    Message message;

    try {
        message = gmail.users().messages().get("me", msgID).setFormat("raw")
                .setFields("historyId,id,internalDate,labelIds,raw,snippet").execute();
    } catch (GoogleJsonResponseException e) {
        Log.d(TAG, "Message no longer exists: " + msgID + " - " + e.getMessage());
        return null;
    }
    if (message == null)
        return null;

    for (String labelID : message.getLabelIds()) {
        if (labelID.equals("CHAT"))
            return null;
    }

    String address = "Unknown";
    mimeMessage = new MimeMessage(session, new ByteArrayInputStream(Base64.decodeBase64(message.getRaw())));

    if (mimeMessage.getFrom()[0] != null) {
        InternetAddress add;
        add = new InternetAddress(mimeMessage.getFrom()[0].toString());

        if (add.getPersonal() != null) {
            address = add.getPersonal();
        } else if (add.getAddress() != null) {
            address = add.getAddress();
        } else {
            address = mimeMessage.getFrom()[0].toString();
        }

    }

    Date date = new Date(message.getInternalDate());
    batch.add(ContentProviderOperation.newInsert(IrisContentProvider.MESSAGES_URI)
            .withValue(IrisContentProvider.MESSAGE_ID, message.getId())
            .withValue(IrisContentProvider.USER_ID, credential.getSelectedAccountName())
            .withValue(IrisContentProvider.HISTORYID, message.getHistoryId().toString())
            .withValue(IrisContentProvider.INTERNALDATE, message.getInternalDate())
            .withValue(IrisContentProvider.DATE,
                    (new SimpleDateFormat("M/d/yy h:mm a", Locale.US).format(date)))
            .withValue(IrisContentProvider.SNIPPET, message.getSnippet())
            .withValue(IrisContentProvider.SUBJECT, mimeMessage.getSubject())
            .withValue(IrisContentProvider.FROM, address)
            .withValue(IrisContentProvider.BODY, message.getSnippet()).build());

    newMessages.add(message.getId());
    newMessageAccounts.add(credential.getSelectedAccountName());

    return message.getHistoryId();

}

From source file:org.opensilk.music.library.drive.client.DriveClient.java

License:Open Source License

@Inject
public DriveClient(HttpTransport httpTransport, JsonFactory jsonFactory, GoogleAccountCredential credential,
        @Named("AppIdentifier") String appIdentifier, @Named("driveLibraryAuthority") String authority) {
    mDrive = new Drive.Builder(httpTransport, jsonFactory, credential).setApplicationName(appIdentifier)
            .build();//  w  w  w .j av a  2  s  .  c  o  m
    mCredential = credential;
    mAuthority = authority;
    mAccount = credential.getSelectedAccountName();
}