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

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

Introduction

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

Prototype

public static GoogleAccountCredential usingOAuth2(Context context, Collection<String> scopes) 

Source Link

Document

Constructs a new instance using OAuth 2.0 scopes.

Usage

From source file:org.opensilk.music.plugin.drive.SessionFactory.java

License:Open Source License

public Session getSession(String accountName) throws IOException, GoogleAuthException {
    Session s = sSessions.get(accountName);
    if (s != null) {
        return s;
    }//from  ww  w.  j  av a  2 s  .c  o m
    final GoogleAccountCredential credential = GoogleAccountCredential
            .usingOAuth2(context, Collections.singleton(DriveScopes.DRIVE_READONLY))
            .setSelectedAccountName(accountName);
    final Drive drive = new Drive.Builder(AndroidHttp.newCompatibleTransport(),
            AndroidJsonFactory.getDefaultInstance(), credential).setApplicationName(APP_NAME).build();
    final String token = credential.getToken();
    final Session holder = new Session(credential, drive, token);
    sSessions.put(accountName, holder);
    return holder;
}

From source file:org.youtube.Youtube_MainActivity.java

License:Apache License

@Override
protected void onCreate(Bundle savedInstanceState) {
    getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    super.onCreate(savedInstanceState);

    mYoutubeUploadsListFragment = new Youtube_UploadsListFragment(getApplicationContext());

    // Check to see if the proper keys and playlist IDs have been set up
    if (!isCorrectlyConfigured()) {
        setContentView(R.layout.youtube_developer_setup_required);
        showMissingConfigurations();/* www.j av a2  s  . c  om*/
    } else {
        setContentView(R.layout.youtube_activity_main);

        ensureLoader();

        credential = GoogleAccountCredential.usingOAuth2(getApplicationContext(),
                Arrays.asList(Youtube_Auth.SCOPES));
        // set exponential backoff policy
        credential.setBackOff(new ExponentialBackOff());

        if (savedInstanceState != null) {
            mChosenAccountName = savedInstanceState.getString(ACCOUNT_KEY);
        } else {
            loadAccount();
        }

        credential.setSelectedAccountName(mChosenAccountName);

        mYoutubeUploadsListFragment = (Youtube_UploadsListFragment) getFragmentManager()
                .findFragmentById(R.id.list_fragment);

    }
}

From source file:org.youtube.Youtube_UploadService.java

License:Apache License

@Override
protected void onHandleIntent(Intent intent) {
    Uri fileUri = intent.getData();/*from   w  w  w. ja va  2  s  .c o  m*/
    String chosenAccountName = intent.getStringExtra(Youtube_MainActivity.ACCOUNT_KEY);

    credential = GoogleAccountCredential.usingOAuth2(getApplicationContext(),
            Lists.newArrayList(Youtube_Auth.SCOPES));
    credential.setSelectedAccountName(chosenAccountName);
    credential.setBackOff(new ExponentialBackOff());

    String appName = getResources().getString(R.string.app_name);
    final YouTube youtube = new YouTube.Builder(transport, jsonFactory, credential).setApplicationName(appName)
            .build();

    try {
        tryUploadAndShowSelectableNotification(fileUri, youtube);
    } catch (InterruptedException e) {
        // ignore
    }
}

From source file:ru.orangesoftware.financisto.activity.PreferencesActivity.java

License:Open Source License

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);

    db = new DatabaseAdapter(this);
    db.open();/*w  w  w  . java2 s  .  com*/
    em = db.em();

    // Initialize credentials and service object.
    mCredential = GoogleAccountCredential.usingOAuth2(getApplicationContext(), Arrays.asList(SCOPES))
            .setBackOff(new ExponentialBackOff());
    setSavedGoogleAccount();

    PreferenceScreen preferenceScreen = getPreferenceScreen();
    Preference pLocale = preferenceScreen.findPreference("ui_language");
    pLocale.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            String locale = (String) newValue;
            MyPreferences.switchLocale(PreferencesActivity.this, locale);
            return true;
        }
    });
    Preference pNewTransactionShortcut = preferenceScreen.findPreference("shortcut_new_transaction");
    pNewTransactionShortcut.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            addShortcut(".activity.TransactionActivity", R.string.transaction, R.drawable.icon_transaction);
            return true;
        }

    });
    Preference pNewTransferShortcut = preferenceScreen.findPreference("shortcut_new_transfer");
    pNewTransferShortcut.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            addShortcut(".activity.TransferActivity", R.string.transfer, R.drawable.icon_transfer);
            return true;
        }
    });
    Preference pDatabaseBackupFolder = preferenceScreen.findPreference("database_backup_folder");
    pDatabaseBackupFolder.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            selectDatabaseBackupFolder();
            return true;
        }
    });
    //        Preference pAuthDropbox = preferenceScreen.findPreference("dropbox_authorize");
    //        pAuthDropbox.setOnPreferenceClickListener(new OnPreferenceClickListener(){
    //            @Override
    //            public boolean onPreferenceClick(Preference arg0) {
    //                authDropbox();
    //                return true;
    //            }
    //        });
    //        Preference pDeauthDropbox = preferenceScreen.findPreference("dropbox_unlink");
    //        pDeauthDropbox.setOnPreferenceClickListener(new OnPreferenceClickListener() {
    //            @Override
    //            public boolean onPreferenceClick(Preference arg0) {
    //                deAuthDropbox();
    //                return true;
    //            }
    //        });
    Preference pExchangeProvider = preferenceScreen.findPreference("exchange_rate_provider");
    pOpenExchangeRatesAppId = preferenceScreen.findPreference("openexchangerates_app_id");
    pExchangeProvider.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            pOpenExchangeRatesAppId.setEnabled(isOpenExchangeRatesProvider((String) newValue));
            return true;
        }

        private boolean isOpenExchangeRatesProvider(String provider) {
            return ExchangeRateProviderFactory.openexchangerates.name().equals(provider);
        }
    });

    Preference pDriveAccount = preferenceScreen.findPreference("google_drive_backup_account");
    pDriveAccount.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            chooseAccount();
            return true;
        }
    });

    Preference pDriveBackupFolder = preferenceScreen.findPreference("backup_folder");
    pDriveBackupFolder.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            chooseDriveFolder();
            return true;
        }
    });

    ArrayList<String> accountNames = new ArrayList<String>();
    ArrayList<String> accountValues = new ArrayList<String>();

    for (ru.orangesoftware.financisto.model.Account account : db.em().getAllAccountsList()) {
        accountNames.add(account.title);
        accountValues.add(String.valueOf(account.id));
    }

    String[] accountEntryNames = accountNames.toArray(new String[accountNames.size()]);
    String[] accountEntryValues = accountValues.toArray(new String[accountValues.size()]);

    ListPreference pPrivatCardAccount = (ListPreference) preferenceScreen
            .findPreference("main_privatbank_card_account");
    pPrivatCardAccount.setEntries(accountEntryNames);
    pPrivatCardAccount.setEntryValues(accountEntryValues);
    //        pPrivatCardAccount.setDefaultValue("");

    ListPreference pCashAccount = (ListPreference) preferenceScreen.findPreference("cache_account");
    pCashAccount.setEntries(accountEntryNames);
    pCashAccount.setEntryValues(accountEntryValues);
    //        pCashAccount.setDefaultValue("");

    ListPreference pSavingsAccount = (ListPreference) preferenceScreen.findPreference("savings_account");
    pSavingsAccount.setEntries(accountEntryNames);
    pSavingsAccount.setEntryValues(accountEntryValues);
    //        pCashAccount.setDefaultValue("");

    ArrayList<String> categoryNames = new ArrayList<String>();
    ArrayList<String> categoryValues = new ArrayList<String>();

    for (Category category : db.em().getAllCategoriesList(false)) {
        categoryNames.add(category.title);
        categoryValues.add(String.valueOf(category.id));
    }

    String[] categoryEntryNames = categoryNames.toArray(new String[categoryNames.size()]);
    String[] categoryEntryValues = categoryValues.toArray(new String[categoryValues.size()]);

    ListPreference pAtmCommisionCategory = (ListPreference) preferenceScreen
            .findPreference("atm_commision_category");
    pAtmCommisionCategory.setEntries(categoryEntryNames);
    pAtmCommisionCategory.setEntryValues(categoryEntryValues);
    //        pCashAccount.setDefaultValue("");

    ListPreference pBankCommisionCategory = (ListPreference) preferenceScreen
            .findPreference("bank_commision_category");
    pBankCommisionCategory.setEntries(categoryEntryNames);
    pBankCommisionCategory.setEntryValues(categoryEntryValues);
    //        pCashAccount.setDefaultValue("");

    //        linkToDropbox();
    setCurrentDatabaseBackupFolder();
    enableOpenExchangeApp();
    updateSelectedAccountPreference();
}

From source file:ru.pnapp.googledrive.GoogleDriveREST.java

License:Apache License

@WorkerThread
synchronized public void connect() throws IOException {
    if (!isEnabled())
        throw new IOException(ERROR_NOT_ENABLED);
    if (drive != null)
        return;/*from ww  w.j a  v a 2 s.c  om*/

    if (!checkGooglePlayServices()) {
        setEnabled(false);
        throw new IOException("Google Play Services not available");
    }

    try {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int status = ContextCompat.checkSelfPermission(mContext, Manifest.permission.GET_ACCOUNTS);
            if (status != PackageManager.PERMISSION_GRANTED) {
                throw new IOException("Access to contacts is required!");
            }
        }

        credential = GoogleAccountCredential.usingOAuth2(mContext, Collections.singleton(mScope.toString()));

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(mContext);
        accountName = preferences.getString(PREF_ACCOUNT_NAME, null);
        if (accountName == null) {
            setEnabled(false);
            if (mContext instanceof Activity) {
                ((Activity) mContext).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ((Activity) mContext).startActivityForResult(credential.newChooseAccountIntent(),
                                REQUEST_ACCOUNT_NAME);
                    }
                });
            }
            throw new IOException("Not authorized, context is " + mContext);
        }

        credential.setSelectedAccountName(accountName);

        drive = new Drive.Builder(httpTransport, jsonFactory, credential)
                .setApplicationName(BuildConfig.APPLICATION_ID).build();

        File file;
        if (mFolder == null)
            file = drive.files().get("root").execute();
        else
            file = drive.files().get(mFolder).execute();
        mFolder = file.getId();
    } catch (UserRecoverableAuthIOException e) {
        final Intent intent = e.getIntent();
        if (mContext instanceof Activity) {
            ((Activity) mContext).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ((Activity) mContext).startActivityForResult(intent, REQUEST_AUTHORIZE);
                }
            });
        }
    } catch (Exception e) {
        throw new IOException("Connect fails: " + e.getMessage());
    }
}