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

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

Introduction

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

Prototype

public final GoogleAccountCredential setSelectedAccountName(String accountName) 

Source Link

Document

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

Usage

From source file:com.zns.comicdroid.activity.Settings.java

License:Open Source License

protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == 101 || requestCode == 201 || requestCode == 301) {
            //Get Account name from result
            mAccount = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
            //Store account         
            SharedPreferences.Editor editor = mPrefs.edit();
            editor.putString(Application.PREF_DRIVE_ACCOUNT, mAccount);
            editor.commit();//from   w w  w .  j  a  v  a  2s  .  c o m
        }

        if (requestCode == 101 || requestCode == 102) {
            //Try to create folder on drive
            DriveWebFolderTaskArg args = new DriveWebFolderTaskArg();
            GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(getApplicationContext(),
                    Arrays.asList(Application.DRIVE_SCOPE_PUBLISH));
            credential.setSelectedAccountName(mAccount);
            args.credentials = credential;
            args.webFolderId = mPrefs.getString(Application.PREF_DRIVE_WEBFOLDERID, null);
            new DriveWebFolderTask() {
                protected void onPostExecute(DriveWebFolderTaskResult result) {
                    if (result.intent != null) {
                        //Not authorized, prompt for authorization
                        startActivityForResult(result.intent, 102);
                    } else if (result.success && result.fileId != null) {
                        //Store url
                        SharedPreferences.Editor editor = mPrefs.edit();
                        editor.putString(Application.PREF_DRIVE_WEBFOLDERID, result.fileId);
                        //Google drive authorized, store status                     
                        editor.putBoolean(Application.PREF_DRIVE_PUBLISH, true);
                        editor.commit();
                        //Upload
                        Intent intent = new Intent(Settings.this, GoogleDriveService.class);
                        intent.putExtra(GoogleDriveService.INTENT_PUBLISH_ONLY, true);
                        startService(intent);
                        //Update link
                        mTvLink.setText(Html.fromHtml("<a href=\"https://googledrive.com/host/" + result.fileId
                                + "/\">" + getResources().getString(R.string.settings_linktext) + "</a>"));
                        mTvLink.setMovementMethod(LinkMovementMethod.getInstance());
                        //Check checkbox
                        setToggleButtonPref(mTbDrivePublish, true, null);
                    } else if (result.fileExists) {
                        Toast.makeText(Settings.this, R.string.error_webfolderexists, Toast.LENGTH_LONG).show();
                        setToggleButtonPref(mTbDrivePublish, false, Application.PREF_DRIVE_PUBLISH);
                    } else {
                        Toast.makeText(Settings.this, R.string.error_webfoldercreate, Toast.LENGTH_SHORT)
                                .show();
                        setToggleButtonPref(mTbDrivePublish, false, Application.PREF_DRIVE_PUBLISH);
                    }
                }
            }.execute(args);
        } else if (requestCode == 201 || requestCode == 202) {
            //Make sure we have access to appdata folder            
            final GoogleAccountCredential credential = GoogleAccountCredential
                    .usingOAuth2(getApplicationContext(), Arrays.asList(Application.DRIVE_SCOPE_BACKUP));
            credential.setSelectedAccountName(mAccount);
            DriveBackupInitTaskArg args = new DriveBackupInitTaskArg();
            args.credentials = credential;
            args.appId = mPrefs.getString(Application.PREF_APP_ID, "");
            new DriveBackupInitTask() {
                protected void onPostExecute(DriveBackupInitTaskResult result) {
                    if (result.intent != null) {
                        //Not authorized, prompt for authorization
                        startActivityForResult(result.intent, 202);
                    } else if (result.success && result.backupAllowed) {
                        //Store preferences
                        SharedPreferences.Editor editor = mPrefs.edit();
                        editor.putBoolean(Application.PREF_DRIVE_BACKUP, true);
                        editor.commit();
                        //Backup
                        BackupManager m = new BackupManager(Settings.this);
                        m.dataChanged();
                        //Check checkbox
                        setToggleButtonPref(mTbDriveBackup, true, null);
                    } else if (!result.backupAllowed) {
                        //User needs to be able to force enabling backup, the appId may be from an uninstalled version
                        new AlertDialog.Builder(Settings.this)
                                .setMessage(getString(R.string.error_backupdisallowed))
                                .setPositiveButton(R.string.settings_forcebackup,
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int id) {
                                                new DriveDisableBackupTask() {
                                                    @Override
                                                    protected void onPostExecute(Boolean result) {
                                                        if (result == Boolean.TRUE) {
                                                            setToggleButtonPref(mTbDriveBackup, false,
                                                                    Application.PREF_DRIVE_BACKUP);
                                                        }
                                                    }
                                                }.execute(credential);
                                            }
                                        })
                                .setNegativeButton(R.string.common_close,
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int id) {
                                                setToggleButtonPref(mTbDriveBackup, false,
                                                        Application.PREF_DRIVE_BACKUP);
                                                dialog.cancel();
                                            }
                                        })
                                .show();
                    } else {
                        Toast.makeText(Settings.this,
                                getString(R.string.error_driveappdataaccess) + ": " + result.errorMessage,
                                Toast.LENGTH_SHORT).show();
                        setToggleButtonPref(mTbDriveBackup, false, Application.PREF_DRIVE_BACKUP);
                    }
                }
            }.execute(args);
        } else if (requestCode == 301 || requestCode == 302) {
            //Request access to restore data
            GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(getApplicationContext(),
                    Arrays.asList(Application.DRIVE_SCOPE_BACKUP));
            credential.setSelectedAccountName(mAccount);
            DriveBackupInitTaskArg args = new DriveBackupInitTaskArg();
            args.credentials = credential;
            args.appId = null;
            new DriveBackupInitTask() {
                protected void onPostExecute(DriveBackupInitTaskResult result) {
                    if (result.intent != null) {
                        //Not authorized, prompt for authorization
                        startActivityForResult(result.intent, 302);
                    } else if (result.success) {
                        //Start restore
                        Intent intent = new Intent(Settings.this, RestoreFromDriveService.class);
                        startService(intent);
                    } else {
                        Toast.makeText(Settings.this, R.string.error_driveappdataaccess, Toast.LENGTH_SHORT)
                                .show();
                    }
                }
            }.execute(args);
        }
    }
}

From source file:com.zns.comicdroid.activity.Settings.java

License:Open Source License

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if (buttonView == mTbDrivePublish) {
        if (isChecked) {
            pickAccount(101);//from ww w .  java 2  s.com
        } else {
            SharedPreferences.Editor editor = mPrefs.edit();
            editor.putBoolean(Application.PREF_DRIVE_PUBLISH, false);
            editor.commit();
        }
    } else if (buttonView == mTbDriveBackup) {
        if (isChecked) {
            pickAccount(201);
        } else {
            mTbDriveBackup.setEnabled(false);
            SharedPreferences.Editor editor = mPrefs.edit();
            editor.putBoolean(Application.PREF_DRIVE_BACKUP, false);
            editor.commit();
            if (mAccount != null) {
                GoogleAccountCredential credential = GoogleAccountCredential
                        .usingOAuth2(getApplicationContext(), Arrays.asList(Application.DRIVE_SCOPE_BACKUP));
                credential.setSelectedAccountName(mAccount);
                new DriveDisableBackupTask() {
                    @Override
                    protected void onPostExecute(Boolean result) {
                        if (mTbDriveBackup != null) {
                            mTbDriveBackup.setEnabled(true);
                        }
                    }
                }.execute(credential);
            }
        }
    } else if (buttonView == mTbBackupWifi) {
        SharedPreferences.Editor editor = mPrefs.edit();
        editor.putBoolean(Application.PREF_BACKUP_WIFIONLY, isChecked);
        editor.commit();
    }
}

From source file:com.zns.comicdroid.service.GoogleDriveService.java

License:Open Source License

private synchronized void Backup(String account, String appId) {
    //Get Service
    Drive service = null;/*w  w w  .  jav a2  s  .c  om*/
    try {
        GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(getApplicationContext(),
                Arrays.asList(Application.DRIVE_SCOPE_BACKUP));
        credential.setSelectedAccountName(account);
        credential.getToken();
        service = new Drive.Builder(AndroidHttp.newCompatibleTransport(), new JacksonFactory(), credential)
                .build();
    } catch (UserRecoverableAuthException e) {
        //We are not authenticated for some reason, notify user.
        NotifyAuthentication();
        return;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return;
    } catch (GoogleAuthException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return;
    }

    //Make sure the current backup is made from the same device
    try {
        com.google.api.services.drive.model.File f = DriveUtil.getFile(service, "appdata",
                BACKUP_META_FILENAME);
        if (f != null) {
            HttpResponse response = service.getRequestFactory()
                    .buildGetRequest(new GenericUrl(f.getDownloadUrl())).execute();
            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getContent()));
            String backupAppId = reader.readLine();
            reader.close();
            response.disconnect();

            if (!backupAppId.equals(appId)) {
                mLogger.appendLog("Unable to backup to drive, appid does not match", Logger.TAG_BACKUP);
                return;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    //------------------Upload current backup to google drive---------------------------
    //Get file path
    String outPath = getApplicationContext().getExternalFilesDir(null).toString() + "/backup";
    File fileData = new File(outPath, BACKUP_DATA_FILENAME);

    //Upload to google drive
    int timeStamp = (int) (System.currentTimeMillis() / 1000L);
    boolean uploadSuccess = true;
    try {
        //Get files to update/insert
        com.google.api.services.drive.model.File dataDriveFile = null;
        com.google.api.services.drive.model.File metaDriveFile = null;
        FileList list = service.files().list().setQ("'appdata' in parents").execute();
        for (com.google.api.services.drive.model.File f : list.getItems()) {
            if (f.getTitle().toLowerCase(Locale.ENGLISH).equals(BACKUP_META_FILENAME)) {
                metaDriveFile = f;
            } else if (f.getTitle().toLowerCase(Locale.ENGLISH).equals(BACKUP_DATA_FILENAME)) {
                dataDriveFile = f;
            }
        }

        //Insert meta         
        ByteArrayContent contentMeta = ByteArrayContent.fromString("text/plain",
                appId + "\n" + Integer.toString(timeStamp));
        com.google.api.services.drive.model.File fMeta = new com.google.api.services.drive.model.File();
        fMeta.setTitle(BACKUP_META_FILENAME);
        fMeta.setMimeType("text/plain");
        fMeta.setParents(Arrays.asList(new ParentReference().setId("appdata")));
        if (metaDriveFile == null) {
            service.files().insert(fMeta, contentMeta).execute();
        } else {
            Update update = service.files().update(metaDriveFile.getId(), null, contentMeta);
            update.setNewRevision(false);
            update.execute();
        }

        //Insert/Update data
        FileContent contentData = new FileContent("application/octet-stream", fileData);
        com.google.api.services.drive.model.File fData = new com.google.api.services.drive.model.File();
        fData.setTitle(BACKUP_DATA_FILENAME);
        fData.setMimeType("application/octet-stream");
        fData.setParents(Arrays.asList(new ParentReference().setId("appdata")));
        if (dataDriveFile == null) {
            service.files().insert(fData, contentData).execute();
        } else {
            Update update = service.files().update(dataDriveFile.getId(), null, contentData);
            update.setNewRevision(false);
            update.execute();
        }
    } catch (Exception e) {
        uploadSuccess = false;
        e.printStackTrace();
    }

    //Success?
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    Editor edit = prefs.edit();
    edit.putBoolean(Application.PREF_BACKUP_SUCCESS, uploadSuccess);
    if (uploadSuccess) {
        mLogger.appendLog("Backup to drive success", Logger.TAG_BACKUP);
        edit.putInt(Application.PREF_BACKUP_LAST, timeStamp);
    } else {
        mLogger.appendLog("Backup to drive failed", Logger.TAG_BACKUP);
    }
    edit.commit();
}

From source file:com.zns.comicdroid.service.GoogleDriveService.java

License:Open Source License

private synchronized void PublishComics(String account, String webFolderId, boolean force) {
    //Get Service
    Drive service = null;/*from w  w  w. j av  a2  s  .c  o  m*/
    try {
        GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(getApplicationContext(),
                Arrays.asList(Application.DRIVE_SCOPE_PUBLISH));
        credential.setSelectedAccountName(account);
        credential.getToken();
        service = new Drive.Builder(AndroidHttp.newCompatibleTransport(), new JacksonFactory(), credential)
                .build();
    } catch (UserRecoverableAuthException e) {
        //We are not authenticated for some reason, notify user.
        NotifyAuthentication();
        return;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return;
    } catch (GoogleAuthException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return;
    }

    //Make sure webfolder still exists
    try {
        com.google.api.services.drive.model.File webFolder = service.files().get(webFolderId).execute();
        if (webFolder == null || webFolder.getExplicitlyTrashed() == Boolean.TRUE) {
            NotifyAuthentication();
            return;
        }
    } catch (IOException e) {
        NotifyAuthentication();
        return;
    }

    //Get some more stuff from context
    String outPath = getApplicationContext().getExternalFilesDir(null).toString() + "/html";
    String imagePath = ((Application) getApplication()).getImagePath(true);

    //Let's get started
    File fileOut = new File(outPath);
    fileOut.mkdirs();
    fileOut = new File(outPath, PUBLISH_INDEX_FILENAME);

    BufferedReader reader = null;
    BufferedWriter writer = null;
    Cursor cursor = null;

    try {
        cursor = mDb.getCursor(
                "SELECT _id, Title, Subtitle, Author, Image, ImageUrl, 1 AS ItemType, 0 AS BookCount, IsBorrowed, AddedDate "
                        + "FROM tblBooks WHERE GroupId = 0 OR ifnull(GroupId, '') = '' " + "UNION "
                        + "SELECT _id, Name AS Title, '' AS Subtitle, '' AS Author, (SELECT Image FROM tblBooks where GroupId = tblGroups._id) AS Image, ImageUrl, 2 AS ItemType, BookCount, 0 AS IsBorrowed, 0 AS PublishDate "
                        + "FROM tblGroups " + "ORDER BY Title",
                null);

        int rowCount = cursor.getCount();
        String line;

        //Read template
        StringBuilder sbTemplate = new StringBuilder();
        reader = new BufferedReader(new InputStreamReader(getResources().openRawResource(R.raw.listtemplate)));
        while ((line = reader.readLine()) != null) {
            sbTemplate.append(line);
        }
        reader.close();

        //Write HTML
        writer = new BufferedWriter(new FileWriter(fileOut));
        reader = new BufferedReader(new InputStreamReader(getResources().openRawResource(R.raw.framework)));
        int i = 0;
        while ((line = reader.readLine()) != null) {
            if (line.trim().equals("#LISTCOMICS#")) {
                while (cursor.moveToNext()) {
                    int id = cursor.getInt(0);
                    String title = nullToEmpty(cursor.getString(1));
                    String subTitle = nullToEmpty(cursor.getString(2));
                    String author = nullToEmpty(cursor.getString(3));
                    String image = nullToEmpty(cursor.getString(4));
                    String imageUrl = nullToEmpty(cursor.getString(5));
                    int type = cursor.getInt(6);
                    int date = cursor.getInt(9);

                    StringBuilder sbChildren = new StringBuilder();

                    String comicLine = sbTemplate.toString();
                    comicLine = comicLine.replace("#TITLE#",
                            title + (type == 1 && !subTitle.equals("") ? " - " + subTitle : ""));
                    comicLine = comicLine.replace("#AUTHOR#", author);
                    comicLine = comicLine.replace("#IMAGEURL#", getImageSrc(imageUrl, image, imagePath));
                    comicLine = comicLine.replace("#ISSUE#", "");
                    comicLine = comicLine.replace("#ISAGGREGATE#", type == 2 ? " Aggregate" : "");
                    comicLine = comicLine.replace("#MARK#", type == 2 ? "<div class=\"Mark\"></div>" : "");
                    comicLine = comicLine.replace("#DATE#", type == 1 ? Integer.toString(date) : "");

                    if (type == 2) {
                        //Render group children
                        List<Comic> comics = mDb.getComics(id);
                        for (Comic comic : comics) {
                            String childComic = sbTemplate.toString();
                            childComic = childComic.replace("#TITLE#",
                                    nullToEmpty(comic.getTitle())
                                            + (!nullToEmpty(comic.getSubTitle()).equals("")
                                                    ? " - " + comic.getSubTitle()
                                                    : ""));
                            childComic = childComic.replace("#AUTHOR#", nullToEmpty(comic.getAuthor()));
                            childComic = childComic.replace("#IMAGEURL#",
                                    getImageSrc(nullToEmpty(comic.getImageUrl()), nullToEmpty(comic.getImage()),
                                            imagePath));
                            childComic = childComic.replace("#ISSUE#",
                                    comic.getIssue() > 0 ? Integer.toString(comic.getIssue()) : "");
                            childComic = childComic.replace("#DATE#",
                                    Integer.toString(comic.getAddedDateTimestamp()));
                            childComic = childComic.replace("#ISAGGREGATE#", "");
                            childComic = childComic.replace("#MARK#", "");
                            childComic = childComic.replace("#CHILDREN#", "");
                            sbChildren.append(childComic);
                        }
                        comicLine = comicLine.replace("#CHILDREN#", sbChildren.toString());
                    } else {
                        comicLine = comicLine.replace("#CHILDREN#", "");
                    }

                    writer.write(comicLine);

                    if (force) {
                        Double part = (((double) i + 1) / (double) rowCount) * 100.0;
                        EventBus.getDefault().post(
                                new ProgressResult(part.intValue(), getString(R.string.progress_publish)));
                        i++;
                    }
                }
            } else {
                writer.write(line);
            }
        }
    } catch (Exception e) {
        //Gotta catch'em all!
        return;
    } finally {
        if (cursor != null)
            cursor.close();
        try {
            if (writer != null)
                writer.close();
            if (reader != null)
                reader.close();
        } catch (IOException e) {
        }
    }

    //Upload to google drive
    if (force) {
        EventBus.getDefault().post(new ProgressResult(20, getString(R.string.progress_publishupload)));
    }

    try {
        //Get current index file
        com.google.api.services.drive.model.File fileIndex = DriveUtil.getFile(service, webFolderId,
                PUBLISH_INDEX_FILENAME);

        //Set content of file
        FileContent content = new FileContent("text/html", fileOut);

        //Insert / Update
        if (fileIndex == null) {
            com.google.api.services.drive.model.File driveFile = new com.google.api.services.drive.model.File();
            driveFile.setTitle(PUBLISH_INDEX_FILENAME);
            driveFile.setMimeType("text/html");
            driveFile.setParents(Arrays.asList(new ParentReference().setId(webFolderId)));
            service.files().insert(driveFile, content).execute();
        } else {
            Update update = service.files().update(fileIndex.getId(), null, content);
            update.setNewRevision(false);
            update.execute();
        }

        mLogger.appendLog("Published to google drive", Logger.TAG_BACKUP);
    } catch (Exception e) {
        mLogger.appendLog("Failed to publish to google drive", Logger.TAG_BACKUP);
        e.printStackTrace();
    }

    if (force) {
        EventBus.getDefault().post(new ProgressResult(100, getString(R.string.progress_publishupload)));
    }
}

From source file:com.zns.comicdroid.service.RestoreFromDriveService.java

License:Open Source License

@Override
protected void onHandleIntent(Intent intent) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    String account = prefs.getString(Application.PREF_DRIVE_ACCOUNT, null);

    com.google.api.services.drive.model.File gFileData = null;

    //Get Service
    Drive service = null;//from   w  w w  .jav  a  2  s  .  co m
    try {
        GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(getApplicationContext(),
                Arrays.asList(Application.DRIVE_SCOPE_BACKUP));
        credential.setSelectedAccountName(account);
        credential.getToken();
        service = new Drive.Builder(AndroidHttp.newCompatibleTransport(), new JacksonFactory(), credential)
                .build();
        gFileData = DriveUtil.getFile(service, "appdata", GoogleDriveService.BACKUP_DATA_FILENAME);
    } catch (Exception e) {
        //Failed to get data from google drive
    }

    //-------------------------Restore Data------------------------------------
    if (gFileData != null && gFileData.getDownloadUrl() != null && gFileData.getDownloadUrl().length() > 0) {
        DBHelper db = DBHelper.getHelper(getApplicationContext());
        String imagePath = ((Application) getApplication()).getImagePath(true);
        DataInputStream in = null;
        try {
            //Get http response for data file
            HttpResponse response = service.getRequestFactory()
                    .buildGetRequest(new GenericUrl(gFileData.getDownloadUrl())).execute();
            in = new DataInputStream(response.getContent());
            //Restore data
            BackupUtil.RestoreDataFromStream(in, db, imagePath, getResources());
        } catch (Exception e) {
            //Restore failed
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
        }
    } else {
        EventBus.getDefault().post(new ProgressResult(100, ""));
    }

    stopSelf();
}

From source file:com.zuluindia.watchpresenter.messaging.MessagingService.java

License:Open Source License

public static Messaging get(Context context) {
    if (messagingService == null) {
        SharedPreferences settings = context.getSharedPreferences("Watchpresenter", Context.MODE_PRIVATE);
        final String accountName = settings.getString(Constants.PREF_ACCOUNT_NAME, null);
        if (accountName == null) {
            Log.i(Constants.LOG_TAG, "Cannot send message. No account name found");
        } else {// w  w  w  .j av a 2  s. c o m
            GoogleAccountCredential credential = GoogleAccountCredential.usingAudience(context,
                    "server:client_id:" + Constants.ANDROID_AUDIENCE);
            credential.setSelectedAccountName(accountName);
            Messaging.Builder builder = new Messaging.Builder(AndroidHttp.newCompatibleTransport(),
                    new GsonFactory(), credential).setRootUrl(Constants.SERVER_URL);

            messagingService = builder.build();
        }
    }
    return messagingService;
}