List of usage examples for com.google.api.client.googleapis.extensions.android.gms.auth GoogleAccountCredential usingOAuth2
public static GoogleAccountCredential usingOAuth2(Context context, Collection<String> scopes)
From source file:com.teo.sample.MainActivity.java
License:Apache License
@Override public void init(Bundle savedInstanceState) { mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this) .addOnConnectionFailedListener(this).addApi(Plus.API).addScope(Plus.SCOPE_PLUS_PROFILE).build(); // add placeholder account account = new MaterialAccount("", "", new ColorDrawable(R.color.cyan_500), this.getResources().getDrawable(R.drawable.bamboo)); this.addAccount(account); // set listener this.setAccountListener(this); //this.replaceDrawerHeader(this.getResources().getDrawable(R.drawable.mat2)); // create sections frag = new FragmentIndex(); section1 = this.newSection("Section 1", frag); section2 = this.newSection("Section 2", new MaterialSectionListener() { @Override//from w w w .j a v a 2s . com public void onClick(MaterialSection section) { Toast.makeText(MainActivity.this, "Section 2 Clicked", Toast.LENGTH_SHORT).show(); section.unSelect(); } }); // recorder section with icon and 10 notifications recorder = this.newSection("Recorder", this.getResources().getDrawable(R.drawable.ic_launcher), frag) .setNotifications(10); // night section with icon, section color and notifications night = this.newSection("Night Section", this.getResources().getDrawable(R.drawable.ic_launcher), frag) .setSectionColor(Color.parseColor("#2196f3"), Color.parseColor("#1565c0")).setNotifications(150); // night section with section color last = this.newSection("Last Section", frag).setSectionColor(Color.parseColor("#ff9800"), Color.parseColor("#ef6c00")); Intent i = new Intent(this, SettingsActivity.class); settingsSection = this.newSection("Settings", this.getResources().getDrawable(R.drawable.ic_launcher), i); // add your sections to the drawer this.addSection(section1); this.addSection(section2); this.addSubheader("Subheader"); this.addSection(recorder); this.addSection(night); this.addDivisor(); this.addSection(last); this.addBottomSection(settingsSection); this.disableLearningPattern(); this.setBackPattern(MaterialNavigationDrawer.BACKPATTERN_CUSTOM); // enable logging Logger.getLogger("com.google.api.client").setLevel(LOGGING_LEVEL); // view and menu //setContentView(R.layout.calendarlist); //listView = (ListView) findViewById(R.id.list); // Google Accounts credential = GoogleAccountCredential.usingOAuth2(this, Collections.singleton(TasksScopes.TASKS)); SharedPreferences settings = getPreferences(Context.MODE_PRIVATE); credential.setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null)); // Tasks client service = new com.google.api.services.tasks.Tasks.Builder(httpTransport, jsonFactory, credential) .setApplicationName("Google-TasksAndroidSample/1.0").build(); // start thread //t.start(); }
From source file:com.tsg.kiwitech.tsgsocialsharing.googleCalendarUtility.TSGGoogleCalendarManager.java
License:Open Source License
private TSGGoogleCalendarManager(Activity activity) { this.activity = activity; this.mContext = activity.getApplicationContext(); mCredential = GoogleAccountCredential.usingOAuth2(mContext, Arrays.asList(SCOPES)) .setBackOff(new ExponentialBackOff()); mProgress = new ProgressDialog(mContext); mProgress.setMessage("Calling Google Calendar API ..."); mProgress.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); }
From source file:com.weebly.opus1269.clipman.backup.DriveServiceHelper.java
License:Open Source License
/** get the DriveService */ @NonNull//from w ww. j a v a 2 s . c o m private Drive getDriveService() throws DriveException { checkAppFolderPermission(); Drive service = null; final HttpTransport httpTransport = new NetHttpTransport(); final JacksonFactory jsonFactory = new JacksonFactory(); final String email = User.INST(mAppCtxt).getEmail(); final Collection<String> scopes = new ArrayList<>(Collections.singletonList(DriveScopes.DRIVE_APPDATA)); if (!TextUtils.isEmpty(email)) { // Use the authenticated account to sign in to the Drive service. GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(mAppCtxt, scopes); credential.setSelectedAccount(new Account(email, "com.google")); service = new Drive.Builder(httpTransport, jsonFactory, credential) .setApplicationName(mAppCtxt.getString(R.string.app_name)).build(); } if (service == null) { throw new DriveException(ERR_INTERNAL); } return service; }
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 ww . j a v a 2 s. co 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);/* w w w .ja v a2s . c o m*/ } 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;/*from w ww .ja v 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(); } 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 ww w . jav a 2s.co 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 . ja v a2s.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:edu.cloud.iot.reception.calendar.EventSampleActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // enable logging Logger.getLogger("com.google.api.client").setLevel(LOGGING_LEVEL); // view and menu setContentView(R.layout.eventlist);//from ww w. j a va 2 s .c o m listView = (ListView) findViewById(R.id.eventlist); Intent intent = getIntent(); VISITOR_NAME = intent.getStringExtra("visitor_name"); Toast msg = Toast.makeText(getBaseContext(), VISITOR_NAME, Toast.LENGTH_LONG); msg.show(); credential = GoogleAccountCredential.usingOAuth2(this, Collections.singleton(CalendarScopes.CALENDAR)); SharedPreferences settings = getPreferences(Context.MODE_PRIVATE); credential.setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null)); // Calendar client client = new com.google.api.services.calendar.Calendar.Builder(transport, jsonFactory, credential) .setApplicationName("calendar-local").build(); listView.setOnItemClickListener(this); }
From source file:it.gmariotti.android.examples.googleaccount.GDriveActivity.java
License:Apache License
/** * Init service/*ww w.java2s .c o m*/ */ private void initService() { mCredential = GoogleAccountCredential.usingOAuth2(this, DriveScopes.DRIVE); if (mAccountName == null) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); mAccountName = prefs.getString(PREF_ACCOUNT_NAME, null); } if (mAccountName != null) { mCredential.setSelectedAccountName(mAccountName); mService = getDriveService(mCredential); } }