com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential Java Examples

The following examples show how to use com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AndroidGoogleDrive.java    From QtAndroidTools with MIT License 9 votes vote down vote up
public boolean authenticate(String AppName, String ScopeName)
{
    final GoogleSignInAccount SignInAccount = GoogleSignIn.getLastSignedInAccount(mActivityInstance);

    if(SignInAccount != null)
    {
        GoogleAccountCredential AccountCredential;
        Drive.Builder DriveBuilder;

        AccountCredential = GoogleAccountCredential.usingOAuth2(mActivityInstance, Collections.singleton(ScopeName));
        AccountCredential.setSelectedAccount(SignInAccount.getAccount());

        DriveBuilder = new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), AccountCredential);
        DriveBuilder.setApplicationName(AppName);
        mDriveService = DriveBuilder.build();

        return true;
    }

    Log.d(TAG, "You have to signin by select account before use this call!");
    return false;
}
 
Example #2
Source File: SendFusionTablesAsyncTask.java    From mytracks with Apache License 2.0 7 votes vote down vote up
private boolean setPermission(Track track, String tableId) throws IOException, GoogleAuthException {
  boolean defaultTablePublic = PreferencesUtils.getBoolean(context,
      R.string.export_google_fusion_tables_public_key,
      PreferencesUtils.EXPORT_GOOGLE_FUSION_TABLES_PUBLIC_DEFAULT);
  if (!defaultTablePublic) {
    return true;
  }
  GoogleAccountCredential driveCredential = SendToGoogleUtils.getGoogleAccountCredential(
      context, account.name, SendToGoogleUtils.DRIVE_SCOPE);
  if (driveCredential == null) {
    return false;
  }
  Drive drive = SyncUtils.getDriveService(driveCredential);
  Permission permission = new Permission();
  permission.setRole("reader");
  permission.setType("anyone");
  permission.setValue("");   
  drive.permissions().insert(tableId, permission).execute();
  
  shareUrl = SendFusionTablesUtils.getMapUrl(track, tableId);
  return true;
}
 
Example #3
Source File: MainActivity.java    From android-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Handles the {@code result} of a completed sign-in activity initiated from {@link
 * #requestSignIn()}.
 */
private void handleSignInResult(Intent result) {
    GoogleSignIn.getSignedInAccountFromIntent(result)
            .addOnSuccessListener(googleAccount -> {
                    Log.d(TAG, "Signed in as " + googleAccount.getEmail());

                    // Use the authenticated account to sign in to the Drive service.
                    GoogleAccountCredential credential =
                        GoogleAccountCredential.usingOAuth2(
                                this, Collections.singleton(DriveScopes.DRIVE_FILE));
                    credential.setSelectedAccount(googleAccount.getAccount());
                    Drive googleDriveService =
                        new Drive.Builder(
                                AndroidHttp.newCompatibleTransport(),
                                new GsonFactory(),
                                credential)
                           .setApplicationName("Drive API Migration")
                           .build();

                    // The DriveServiceHelper encapsulates all REST API and SAF functionality.
                    // Its instantiation is required before handling any onClick actions.
                    mDriveServiceHelper = new DriveServiceHelper(googleDriveService);
                })
            .addOnFailureListener(exception -> Log.e(TAG, "Unable to sign in.", exception));
}
 
Example #4
Source File: GAEService.java    From security-samples with Apache License 2.0 6 votes vote down vote up
private void initFido2GAEService() {
    if (fido2Service != null) {
        return;
    }
    if (googleSignInAccount == null) {
        return;
    }
    GoogleAccountCredential credential =
            GoogleAccountCredential.usingAudience(
                    context, "server:client_id:" + Constants.SERVER_CLIENT_ID);
    credential.setSelectedAccountName(googleSignInAccount.getEmail());
    Log.d(TAG, "credential account name " + credential.getSelectedAccountName());

    Fido2RequestHandler.Builder builder =
            new Fido2RequestHandler.Builder(
                    AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), credential)
                    .setGoogleClientRequestInitializer(
                            new GoogleClientRequestInitializer() {
                                @Override
                                public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest)
                                        throws IOException {
                                    abstractGoogleClientRequest.setDisableGZipContent(true);
                                }
                            });
    fido2Service = builder.build();
}
 
Example #5
Source File: Auth.java    From UTubeTV with The Unlicense 6 votes vote down vote up
public static GoogleAccountCredential getCredentials(Context ctx, boolean useDefaultAccount) {
  if (credential == null) {
    List<String> scopes = Arrays.asList(YouTubeScopes.YOUTUBE);

    credential = GoogleAccountCredential.usingOAuth2(ctx.getApplicationContext(), scopes);

    // add account name if we have it
    String accountName = null;

    if (useDefaultAccount)
      accountName = accountName(ctx);

    if (accountName != null)
      credential.setSelectedAccountName(accountName);
  }

  return credential;
}
 
Example #6
Source File: TictactoeActivity.java    From appengine-endpoints-tictactoe-android with Apache License 2.0 6 votes vote down vote up
/**
 * Called when the activity is first created. It displays the UI, checks
 * for the account previously chosen to sign in (if available), and
 * configures the service object.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  settings = getSharedPreferences(TAG, 0);
  credential = GoogleAccountCredential.usingAudience(this, ClientCredentials.AUDIENCE);
  setAccountName(settings.getString(PREF_ACCOUNT_NAME, null));

  Tictactoe.Builder builder = new Tictactoe.Builder(
      AndroidHttp.newCompatibleTransport(), new GsonFactory(),
      credential);
  service = builder.build();

  if (credential.getSelectedAccountName() != null) {
    onSignIn();
  }

  Logger.getLogger("com.google.api.client").setLevel(LOGGING_LEVEL);
}
 
Example #7
Source File: CloudBackend.java    From io2014-codelabs with Apache License 2.0 6 votes vote down vote up
private Mobilebackend getMBSEndpoint() {

        // check if credential has account name
        final GoogleAccountCredential gac = mCredential == null
                || mCredential.getSelectedAccountName() == null ? null : mCredential;

        // create HttpRequestInitializer
        HttpRequestInitializer hri = new HttpRequestInitializer() {
            @Override
            public void initialize(HttpRequest request) throws IOException {
                request.setBackOffPolicy(new ExponentialBackOffPolicy());
                if (gac != null) {
                    gac.initialize(request);
                }
            }
        };

        // build MBS builder
        // (specify gac or hri as the third parameter)
        return new Mobilebackend.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(),
                hri)
                .setRootUrl(Consts.ENDPOINT_ROOT_URL).build();
    }
 
Example #8
Source File: CloudBackendFragment.java    From io2014-codelabs with Apache License 2.0 6 votes vote down vote up
/**
 * Subclasses may override this to execute initialization of the activity.
 * If it uses any CloudBackend features, it should be executed inside
 * {@link #onCreateFinished()} that will be called after CloudBackend
 * initializations such as user authentication.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);

    // init backend
    mCloudBackend = new CloudBackendMessaging(getActivity());

    // create credential
    mCredential = GoogleAccountCredential.usingAudience(getActivity(), Consts.AUTH_AUDIENCE);
    mCloudBackend.setCredential(mCredential);

    signInAndSubscribe(false);

    LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mMsgReceiver,
            new IntentFilter(GCMIntentService.BROADCAST_ON_MESSAGE));
}
 
Example #9
Source File: MessagingService.java    From watchpresenter with Apache License 2.0 6 votes vote down vote up
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 {
            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;
}
 
Example #10
Source File: TGDriveBrowserLogin.java    From tuxguitar with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void process() {
	this.authRequestResultHandler = this.createAuthRequestResultHandler();
	this.accountRequestResultHandler = this.createAccountRequestResultHandler();
	
	this.activity.getResultManager().addHandler(this.authRequestCode, this.authRequestResultHandler);
   	this.activity.getResultManager().addHandler(this.accountRequestCode, this.accountRequestResultHandler);
   	
	this.credential = GoogleAccountCredential.usingOAuth2(this.activity, Collections.singleton(DriveScopes.DRIVE));
	if(!this.settings.isDefaultAccount()) {
		this.credential.setSelectedAccountName(this.settings.getAccount());
	} else {
		String defaultAccount = this.getDefaultAccount();
		if( defaultAccount != null ) {
			this.credential.setSelectedAccountName(defaultAccount);
		}
	}
	this.createTokenAsyncTask().execute((Void) null);
}
 
Example #11
Source File: TGDriveBrowser.java    From tuxguitar with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void open(final TGBrowserCallBack<Object> cb){
	try {
		this.drive = null;
		this.folder = null;
		this.httpTransport = AndroidHttp.newCompatibleTransport();
		
		TGDriveBrowserLogin login = new TGDriveBrowserLogin(this.findActivity(), this.settings, new TGBrowserCallBack<GoogleAccountCredential>() {
			public void onSuccess(GoogleAccountCredential credential) {
				Drive.Builder builder = new Drive.Builder(TGDriveBrowser.this.httpTransport, GsonFactory.getDefaultInstance(), credential);
				builder.setApplicationName(findActivity().getString(R.string.gdrive_application_name));
				TGDriveBrowser.this.drive = builder.build();
				
				cb.onSuccess(null);
			}
			
			public void handleError(Throwable throwable) {
				cb.handleError(throwable);
			}
		});
		login.process();
	} catch (Throwable e) {
		cb.handleError(e);
	}
}
 
Example #12
Source File: GoogleUtils.java    From mytracks with Apache License 2.0 6 votes vote down vote up
/**
 * Searches Google Spreadsheets.
 * 
 * @param context the context
 * @param accountName the account name
 * @return the list of spreadsheets matching the title. Null if unable to
 *         search.
 */
public static List<File> searchSpreadsheets(Context context, String accountName) {
  try {
    GoogleAccountCredential googleAccountCredential = SendToGoogleUtils
        .getGoogleAccountCredential(context, accountName, SendToGoogleUtils.DRIVE_SCOPE);
    if (googleAccountCredential == null) {
      return null;
    }

    Drive drive = SyncUtils.getDriveService(googleAccountCredential);
    com.google.api.services.drive.Drive.Files.List list = drive.files().list().setQ(String.format(
        Locale.US, SendSpreadsheetsAsyncTask.GET_SPREADSHEET_QUERY, SPREADSHEETS_NAME));
    return list.execute().getItems();
  } catch (Exception e) {
    Log.e(TAG, "Unable to search spreadsheets.", e);
  }
  return null;
}
 
Example #13
Source File: MainActivity.java    From apps-script-mobile-addons with Apache License 2.0 6 votes vote down vote up
/**
 * Attempts to initialize credentials and service object (prior to a call
 * to the API); uses the account provided by the calling app. This
 * requires the GET_ACCOUNTS permission to be explicitly granted by the
 * user; this will be requested here if it is not already granted. The
 * AfterPermissionGranted annotation indicates that this function will be
 * rerun automatically whenever the GET_ACCOUNTS permission is granted.
 */
@AfterPermissionGranted(REQUEST_PERMISSION_GET_ACCOUNTS)
private void createCredentialsAndService() {
    if (EasyPermissions.hasPermissions(
            MainActivity.this, Manifest.permission.GET_ACCOUNTS)) {
        mCredential = GoogleAccountCredential.usingOAuth2(
                getApplicationContext(), Arrays.asList(SCOPES))
                .setBackOff(new ExponentialBackOff())
                .setSelectedAccountName(mAccount.name);
        mService = new com.google.api.services.script.Script.Builder(
                mTransport, mJsonFactory, setHttpTimeout(mCredential))
                .setApplicationName(getString(R.string.app_name))
                .build();
        updateButtonEnableStatus();

        // Callback to retry the API call with valid service/credentials
        callAppsScriptTask(mLastFunctionCalled);
    } else {
        // Request the GET_ACCOUNTS permission via a user dialog
        EasyPermissions.requestPermissions(
                MainActivity.this,
                getString(R.string.get_accounts_rationale),
                REQUEST_PERMISSION_GET_ACCOUNTS,
                Manifest.permission.GET_ACCOUNTS);
    }
}
 
Example #14
Source File: YouTubeSingleton.java    From YouTube-In-Background with MIT License 6 votes vote down vote up
private YouTubeSingleton(Context context)
{
    String appName = context.getString(R.string.app_name);
    credential = GoogleAccountCredential
            .usingOAuth2(context, Arrays.asList(SCOPES))
            .setBackOff(new ExponentialBackOff());

    youTube = new YouTube.Builder(
            new NetHttpTransport(),
            new JacksonFactory(),
            httpRequest -> {}
    ).setApplicationName(appName).build();

    youTubeWithCredentials = new YouTube.Builder(
            new NetHttpTransport(),
            new JacksonFactory(),
            credential
    ).setApplicationName(appName).build();
}
 
Example #15
Source File: BaseMainDbActivity.java    From dbsync with Apache License 2.0 6 votes vote down vote up
private void handleSignInResult(Intent result) {
    GoogleSignIn.getSignedInAccountFromIntent(result)
            .addOnSuccessListener(googleAccount -> {
                Log.d(TAG, "Signed in as " + googleAccount.getEmail());

                // Use the authenticated account to sign in to the Drive service.
                GoogleAccountCredential credential =
                        GoogleAccountCredential.usingOAuth2(
                                this, Arrays.asList(DriveScopes.DRIVE_FILE, DriveScopes.DRIVE_METADATA, DriveScopes.DRIVE_READONLY,
                                        DriveScopes.DRIVE_METADATA_READONLY, DriveScopes.DRIVE_PHOTOS_READONLY));
                credential.setSelectedAccount(googleAccount.getAccount());

                googleDriveService =
                        new com.google.api.services.drive.Drive.Builder(
                                AndroidHttp.newCompatibleTransport(),
                                new GsonFactory(),
                                credential)
                                .setApplicationName("Drive API DBSync")
                                .build();

                // The DriveServiceHelper encapsulates all REST API and SAF functionality.
                // Its instantiation is required before handling any onClick actions.
                //mDriveServiceHelper = new DriveServiceHelper(googleDriveService);
            })
            .addOnFailureListener(exception -> Log.e(TAG, "Unable to sign in.", exception));
}
 
Example #16
Source File: GoogleDriveApiImpl.java    From science-journal with Apache License 2.0 6 votes vote down vote up
@Override
public DriveApi init(
    HttpTransport transport,
    JsonFactory jsonFactory,
    AppAccount appAccount,
    Context applicationContext) {

  List<String> scopeList = Arrays.asList(SCOPES);
  GoogleAccountCredential credential =
      GoogleAccountCredential.usingOAuth2(applicationContext, scopeList)
          .setBackOff(new ExponentialBackOff())
          .setSelectedAccount(appAccount.getAccount());

  this.driveApi =
      new Drive.Builder(transport, jsonFactory, credential)
          .setApplicationName(applicationContext.getPackageName())
          .build();

  return this;
}
 
Example #17
Source File: BaseMainDbActivity.java    From dbsync with Apache License 2.0 6 votes vote down vote up
private void handleSignInONRecnnect() {
    GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);

    if  (account != null ){
        Log.d(TAG, "Signed in as " + account.getEmail());

        // Use the authenticated account to sign in to the Drive service.
        GoogleAccountCredential credential =
                GoogleAccountCredential.usingOAuth2(
                        this, Collections.singleton(DriveScopes.DRIVE_FILE));
        credential.setSelectedAccount(account.getAccount());

        googleDriveService =
                new com.google.api.services.drive.Drive.Builder(
                        AndroidHttp.newCompatibleTransport(),
                        new GsonFactory(),
                        credential)
                        .setApplicationName("Drive API DBSync")
                        .build();
    }
}
 
Example #18
Source File: GAEService.java    From android-fido with Apache License 2.0 6 votes vote down vote up
private void initFido2GAEService() {
    if (fido2Service != null) {
        return;
    }
    if (googleSignInAccount == null) {
        return;
    }
    GoogleAccountCredential credential =
            GoogleAccountCredential.usingAudience(
                    context, "server:client_id:" + Constants.SERVER_CLIENT_ID);
    credential.setSelectedAccountName(googleSignInAccount.getEmail());
    Log.d(TAG, "credential account name " + credential.getSelectedAccountName());

    Fido2RequestHandler.Builder builder =
            new Fido2RequestHandler.Builder(
                    AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), credential)
                    .setGoogleClientRequestInitializer(
                            new GoogleClientRequestInitializer() {
                                @Override
                                public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest)
                                        throws IOException {
                                    abstractGoogleClientRequest.setDisableGZipContent(true);
                                }
                            });
    fido2Service = builder.build();
}
 
Example #19
Source File: RestApiActivity.java    From google-services with Apache License 2.0 5 votes vote down vote up
@Override
protected List<Person> doInBackground(Account... accounts) {
    if (mActivityRef.get() == null) {
        return null;
    }

    Context context = mActivityRef.get().getApplicationContext();
    try {
        GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(
                context,
                Collections.singleton(CONTACTS_SCOPE));
        credential.setSelectedAccount(accounts[0]);

        PeopleService service = new PeopleService.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential)
                .setApplicationName("Google Sign In Quickstart")
                .build();

        ListConnectionsResponse connectionsResponse = service
                .people()
                .connections()
                .list("people/me")
                .setFields("names,emailAddresses")
                .execute();

        return connectionsResponse.getConnections();

    } catch (UserRecoverableAuthIOException recoverableException) {
        if (mActivityRef.get() != null) {
            mActivityRef.get().onRecoverableAuthException(recoverableException);
        }
    } catch (IOException e) {
        Log.w(TAG, "getContacts:exception", e);
    }

    return null;
}
 
Example #20
Source File: CloudBackendAsync.java    From io2014-codelabs with Apache License 2.0 5 votes vote down vote up
public ContinuousQueryHandler(final CloudCallbackHandler<List<CloudEntity>> handler,
                              final CloudQuery query, final GoogleAccountCredential credential) {
    this.handler = handler;
    this.query = query;
    this.credential = credential;
    uiThreadHandler = new Handler();
}
 
Example #21
Source File: CheckupReminders.java    From Crimson with Apache License 2.0 5 votes vote down vote up
public MakeRequestTask(GoogleAccountCredential credential) {
    HttpTransport transport = AndroidHttp.newCompatibleTransport();
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    mService = new com.google.api.services.calendar.Calendar.Builder(
            transport, jsonFactory, credential)
            .setApplicationName("Google Calendar API Android Quickstart")
            .build();
}
 
Example #22
Source File: ConferenceUtils.java    From conference-central-android-app with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Build and returns an instance of {@link com.appspot.udacity_extras.conference.Conference}
 *
 * @param context
 * @param email
 * @return
 */
public static com.appspot.udacity_extras.conference.Conference buildServiceHandler(
        Context context, String email) {
    GoogleAccountCredential credential = GoogleAccountCredential.usingAudience(
            context, AppConstants.AUDIENCE);
    credential.setSelectedAccountName(email);

    com.appspot.udacity_extras.conference.Conference.Builder builder
            = new com.appspot.udacity_extras.conference.Conference.Builder(
            AppConstants.HTTP_TRANSPORT,
            AppConstants.JSON_FACTORY, credential);
    builder.setApplicationName("conference-central-server");
    return builder.build();
}
 
Example #23
Source File: SignInActivity.java    From solutions-mobile-shopping-assistant-android-client with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves the previously used account name from the application preferences and checks if the
 * credential object can be set to this account.
 */
private boolean isSignedIn() {
  credential = GoogleAccountCredential.usingAudience(this, AUDIENCE);
  SharedPreferences settings = getSharedPreferences("MobileAssistant", 0);
  String accountName = settings.getString(ACCOUNT_NAME_SETTING_NAME, null);
  credential.setSelectedAccountName(accountName);

  return credential.getSelectedAccount() != null;
}
 
Example #24
Source File: MainActivity.java    From watchpresenter with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    settings = getSharedPreferences(Constants.SETTINGS_NAME, MODE_PRIVATE);
    registered = settings.getBoolean(Constants.PREF_REGISTERED, false);
    vibration = settings.getBoolean(Constants.PREF_VIBRATION, true);
    credential = GoogleAccountCredential.usingAudience(this,
            "server:client_id:" + Constants.ANDROID_AUDIENCE);
    setSelectedAccountName(settings.getString(Constants.PREF_ACCOUNT_NAME, null));
    if (credential.getSelectedAccountName() != null) {
        Log.d(Constants.LOG_TAG, "User already logged in");
    } else {
        Log.d(Constants.LOG_TAG, "User not logged in. Requesting user...");
        launchChooseAccount();
    }
    try {
        versionCode = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
        versionName = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
        Log.d(Constants.LOG_TAG, "Pagage name: " + getPackageName());
        Log.d(Constants.LOG_TAG, "Version code: " + versionCode);
        Log.d(Constants.LOG_TAG, "Version name: " + versionName);
    } catch (PackageManager.NameNotFoundException e) {
        Log.e(Constants.LOG_TAG, "Cannot retrieve app version", e);
    }
    registerReceiver(broadcastReceiver, new IntentFilter(ACTION_STOP_MONITORING));

    wearController = new WearController(this);



}
 
Example #25
Source File: ShortyzApplication.java    From shortyz with GNU General Public License v3.0 5 votes vote down vote up
public void updateCredential(SharedPreferences prefs){
	credential = GoogleAccountCredential.usingOAuth2(
			getApplicationContext(), Arrays.asList(GMConstants.SCOPES))
			.setBackOff(new ExponentialBackOff())
			.setSelectedAccountName(prefs.getString(GMConstants.PREF_ACCOUNT_NAME, null));
	if(credential != null && credential.getSelectedAccount() != null) {
		gmailService = new com.google.api.services.gmail.Gmail.Builder(
				transport, jsonFactory, credential)
				.setApplicationName("Shortyz")
				.build();
	} else {
		gmailService = null;
	}
}
 
Example #26
Source File: TGDriveBrowserLogin.java    From tuxguitar with GNU Lesser General Public License v2.1 5 votes vote down vote up
public TGDriveBrowserLogin(TGActivity activity, TGDriveBrowserSettings settings, TGBrowserCallBack<GoogleAccountCredential> callback) {
	this.activity = activity;
	this.settings = settings;
	this.callback = callback;
	this.authRequestCode = this.activity.getResultManager().createRequestCode();
	this.accountRequestCode = this.activity.getResultManager().createRequestCode();
}
 
Example #27
Source File: YouTubeSearch.java    From YouTube-In-Background with MIT License 5 votes vote down vote up
public YouTubeSearch(Activity activity, Fragment playlistFragment)
{
    this.activity = activity;
    this.playlistFragment = playlistFragment;
    handler = new Handler();
    credential = GoogleAccountCredential.usingOAuth2(activity.getApplicationContext(),
            Arrays.asList(Auth.SCOPES));

    // set exponential backoff policy
    credential.setBackOff(new ExponentialBackOff());
    appName = activity.getResources().getString(R.string.app_name);
    language = Locale.getDefault().getLanguage();
}
 
Example #28
Source File: SyncTestUtils.java    From mytracks with Apache License 2.0 5 votes vote down vote up
/**
 * Gets drive object of Google Drive.
 * 
 * @param context the context of application
 * @return a Google Drive object
 */
public static Drive getGoogleDrive(Context context) throws IOException, GoogleAuthException {
  String googleAccount = PreferencesUtils.getString(context, R.string.google_account_key,
      PreferencesUtils.GOOGLE_ACCOUNT_DEFAULT);
  GoogleAccountCredential credential = SendToGoogleUtils.getGoogleAccountCredential(context,
      googleAccount, SendToGoogleUtils.DRIVE_SCOPE);
  return SyncUtils.getDriveService(credential);
}
 
Example #29
Source File: BaseGmailProvider.java    From PrivacyStreams with Apache License 2.0 5 votes vote down vote up
private void checkGmailApiRequirements() {


        String accountName = PreferenceManager.getDefaultSharedPreferences(getContext())
                .getString(PREF_ACCOUNT_NAME, null);

        if (accountName != null) {
            GoogleAccountCredential mCredential = GoogleAccountCredential.usingOAuth2(
                    getContext().getApplicationContext(), Arrays.asList(SCOPES))
                    .setBackOff(new ExponentialBackOff());
            mCredential.setSelectedAccountName(accountName);

            if (!DeviceUtils.isGooglePlayServicesAvailable(getContext())) {
                DeviceUtils.acquireGooglePlayServices(getContext());
            }
            else{
                mService = new Gmail.Builder(
                        AndroidHttp.newCompatibleTransport(), JacksonFactory.getDefaultInstance(), mCredential)
                        .setApplicationName(AppUtils.getApplicationName(getContext()))
                        .build();
                authorized = true;
            }


        } else {
            GmailAuthorizationActivity.setListener(this);
            getContext().startActivity(new Intent(getContext(), GmailAuthorizationActivity.class));
        }

    }
 
Example #30
Source File: TaskListFragment.java    From SimplePomodoro-android with MIT License 5 votes vote down vote up
private void initGoogleTask(){
		Logger.getLogger("com.google.api.client").setLevel(LOGGING_LEVEL);
		credential =
		        GoogleAccountCredential.usingOAuth2(getActivity(), Collections.singleton(TasksScopes.TASKS));
		credential.setSelectedAccountName(SettingUtility.getAccountName());
		// Tasks client
		service =
		        new com.google.api.services.tasks.Tasks.Builder(transport, jsonFactory, credential)
		            .setApplicationName("SimplePomodoro").build();
		checkGooglePlayServicesAvailable();
//		}
	}