I am new to Google API. By following the official Google API sample (https://developers.google.com/android/guides/api-client?authuser=0), I tried to create a DriveResourceClient object to connect my app with Google Drive. Unfortunately, I found that DriveResourceClient is deprecated. I wonder if the official guide I am reading is the latest version or not. If not, is there any latest Google API guide I can rely on? The guide I am currently reading was last updated on March 13, 2019.
Thanks.
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
// Get the app's Drive folder
DriveResourceClient client = Drive.getDriveResourceClient(this,account);
client.getAppFolder().addOnCompleteListener(this, new OnCompleteListener<DriveFolder>() {
#Override
public void onComplete(#NonNull Task<DriveFolder>() {
// ...
}
});
Check out this
This is the Drive REST API.
Download by link: https://github.com/gsuitedevs/android-samples.git
Open project "deprecation". This example will help access account and download files by SAF. If you received your application credentials in the developer console: https://console.cloud.google.com
Related
I have implemented Braintree SDK which supports pay using Paypal, Credit or Debit Card and Google Pay.
All are working except Google Pay.
I am getting following error while selecting payment method as GooglePay.
This merchant is not enabled for Google Pay
Even I have enabled Google Pay option on Braintree console.
following is the code for implementation:
Code on Pay button click:
DropInRequest dropInRequest = new DropInRequest()
.amount(strAmount)
.googlePaymentRequest(getGooglePaymentRequest())
.tokenizationKey("production_key_xxxxxxxxx");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
startActivityForResult(dropInRequest.getIntent(getActivity()), 399);
}
private GooglePaymentRequest getGooglePaymentRequest() {
return new GooglePaymentRequest()
.transactionInfo(TransactionInfo.newBuilder()
.setTotalPrice(strAmount)
.setCurrencyCode("USD")
.setTotalPriceStatus(WalletConstants.TOTAL_PRICE_STATUS_FINAL)
.build())
.emailRequired(true);
}
Help would be appreciated.
Full disclosure: I work at Braintree. If you have any further questions, feel free to contact
support.
It looks like you're trying to pass the incorrect Google Pay object for a standalone Google Pay integration through Braintree into your Drop-in UI.
If you haven't already, you need to include the Google Pay meta tag in your AndroidManifest.xml:
<meta-data android:name="com.google.android.gms.wallet.api.enabled" android:value="true"/>
Then, construct a GooglePaymentRequest object and pass it to your DropInRequest object. The object may look something like:
private void enableGooglePay(DropInRequest dropInRequest) {
GooglePaymentRequest googlePaymentRequest = new GooglePaymentRequest()
.transactionInfo(TransactionInfo.newBuilder()
.setTotalPrice("1.00")
.setTotalPriceStatus(WalletConstants.TOTAL_PRICE_STATUS_FINAL)
.setCurrencyCode("USD")
.build())
.billingAddressRequired(true); // We recommend collecting and passing billing address information with all Google Pay transactions as a best practice.
dropInRequest.googlePaymentRequest(googlePaymentRequest);
}
You can find more information about this in our developer docs.
To use the Google Pay API in production, you need to have it enabled for your app on Google's side as well.
Their Integration checklist is a good place to start, specifically it has a section called Requesting production access
You also need to add googleMerchantId("YOUR-MERCHANT-ID")
The merchantId parameter inside PaymentDataRequest must be set to the value provided in your Google Pay Developer profile.
https://developers.google.com/pay/api/web/support/troubleshooting#merchantId
It's been a while since I worked with Google Play Services and I'm now implementing a feature that requires location tracking. After following a dated example that used GoogleApiClient, I found this post about the new Location APIs at Android Developers blog:
https://android-developers.googleblog.com/2017/06/reduce-friction-with-new-location-apis.html
FusedLocationProviderClient client =
LocationServices.getFusedLocationProviderClient(this);
client.requestLocationUpdates(LocationRequest.create(), pendingIntent)
.addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
Log.d("MainActivity", "Result: " + task.getResult());
}
});
}
What caught my attention was something written at the bottom of the post, saying:
The new API will automatically resolve certain connection failures for
you, so you don't need to write code that for things like prompting
the user to update Google Play services.
Since I've already written that piece of code using GoogleApiAvailabilty I'm curious if it's safe to just remove it and let the FusedLocationProviderClient take care of it?
I've tried to find another source to verify this but failed, not really satisfied with half a line at the bottom of a blog post, hence posting the question here.
Ok so I'll answer my own question after a quick test. I temporarily removed the checks that made sure Google Play Services was available and the correct version. Then installed the app on an emulator without Google Play Services and when I try to use the LocationServices API I get a sticky headsup notification saying:
[app name] won't run unless you update Google Play Services.
So I guess it's safe to remove the checks.
Worth noting is that it seems the listeners (Success/Failure/Complete) are not called unless the user actually interacts with the notification, if they for example just press something else in your apps UI, the listeners were not called.
I'm trying to use the YouTubeData API with OAuth 2.0 authentication on Android, and i'm kind of struggling with it.
I've searched a lot online, but there's not much help for the Android implementation.
First of all, it's not clear to me what's the best way to obtain an OAuth token. In the doc they suggest that for Android is better to obtain it using the Google Play services lib. Is that true? if yes, it should be pretty trivial following this guide: https://developers.google.com/android/guides/http-auth.
But at this point i will have the token in a String object .. how should I use it with the YouTubeData API? Should I place it somewhere in the YouTube.Builder ?
YouTube youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName("AppName").build();
if yes, does anyone know where?
Searching on StackOverflow i've come across this question: What to do after getting Auth Token - Android Youtube API. Here Ibrahim Ulukaya says it's better to use GoogleAccountCredential. For what i've understood (Access to Google API - GoogleAccountCredential.usingOAuth2 vs GoogleAuthUtil.getToken()) the Android version of GoogleAccountCredential should use the GoogleAuthUtil provided from the Google Play services lib, so it could be pretty useful to simplify the process. I've looked at the sample project suggested from Ibrahim Ulukaya (https://github.com/youtube/yt-direct-lite-android) and i've implemented everything as he does. But it doesn't seem to work very well as i'm only obtaining this message in the logcat: "There was an IO error: com.google.android.gms.auth.UserRecoverableAuthException: NeedPermission : null".
(Note that I've enabled all the required APIs on the Google Console, and created the Client ID for my app)
At this point i'm kind of lost.
Should I use directly the GoogleAuthUtil from the Google Play services lib? in this case once obtained the token as a String how can i use it with the YouTubeData APIs?
Or should I use the GoogleAccountCredential ? in this case someone knows how can I solve the "NeedPersmission : null" error?
---- EDIT:
details on what my app is trying to do: being this my first experience with this kind of APIs I started from the easy stuff: retrieve video information and then play those videos, without any user authentication. I managed to do that pretty easily, but for my app's purpose i need to access the user data, in particular users must be able to like and comment videos.
So I started implementing OAuth2, trying to do the same exact queries I was doing before (retrieve video info).
Wow. The documentation on this is super confusing. Full disclosure, I'm not an Android developer but I am a Java developer who has worked with Google apps and OAuth2.
Google Play or not Google Play? First off, Google Play Services will only be available on Android devices with Google Play Services installed (so not OUYA, Amazon devices, etc.). Google state that "the Google Play library will give you the best possible performance and experience.".
There are numerous discussions (e.g. here, here) from actual Android developers that list the various merits of Google Play verses other techniques. I would imagine that once you are able to get your application working using one method, then it should be an easy enough to change if you so desire.
Much of the example code about uses the Android AccountManager (Tasks and Calendars being favourite examples) so that is what I will show.
Your example code looks like it might be for a simple search, I would guess that many of the YouTube API interactions do not require OAuth2, in other code I've seen this empty HttpRequestInitializer implementation referred to as a no-op function. (e.g. GeolocationSearch.java).
It sounds like you want access to YouTube API operations that need account credentials. You can do something similar to this Android Calendar example (CalendarSampleActivity.java) except with YouTube, like the example answer from here.
// Google Accounts
credential = GoogleAccountCredential.usingOAuth2(this, YouTubeScopes.YOUTUBE, YouTubeScopes.YOUTUBE_READONLY);
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
credential.setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null));
// YouTube client
service =
new com.google.api.services.youtube.YouTube.Builder(transport, jsonFactory, credential)
.setApplicationName("Google-YouTubeAndroidSample/1.0").build();
I hope this helps.
In the initialize method of the HttpRequestInitializer you can set headers of the request. According to Googles documention for Oath2 for devices https://developers.google.com/identity/protocols/OAuth2ForDevices if you have an access token you should put it in the Authorization: Bearer HTTP header.
YouTube youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
request.put("Authorization", "Bearer " + yourAccessTokenString);
}
}).setApplicationName("AppName").build();
Remember the space after the Bearer in the authorization header value
I'm currently trying to create a new Google Spreadsheet file using the Google Drive Android API. At the moment, this is the content of my ResultCallback class:
#Override
public void onResult(ContentsResult result) {
if (!result.getStatus().isSuccess()) {
// Handle error
return;
}
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle("My Spreadsheet")
.setMimeType("application/vnd.google-apps.spreadsheet").build();
Drive.DriveApi.getRootFolder(mGoogleApiClient)
.createFile(mGoogleApiClient, changeSet, result.getContents())
.setResultCallback(fileCallback);
}
Every time I run the app I get the warning log "Upload failed HTTP status 400". However, if I change the MIME type to any non-Google service (eg. text/plain, application/vnd.ms-excel, etc.), the file is created successfully. Is this happening because I cannot create empty Google Docs files using the API?
Thank you.
Maybe the problem is that you are trying to upload Google spreadsheet without any body? Or maybe you should try to achieve what you want with pure Java SDK API?
Here is few links:
How do I upload file to google drive from android
https://developers.google.com/drive/android/create-file
I am also analyzing possibilities of integration Android client with Google Drive and apparently there is a way but not using the Drive API but Google Spreadsheets API directly to create and modify Google Spreadsheets.
Check this question
I like to integrate Facebook, twitter and Google plus to my app, so that using the app, user can update their status. Therefore I like to know how this can be done.
Thanks
I would highly recommend not to use those SDK since they contain a lot of bugs, and are not very reliable as far as I've seen.
If you just want to share simple text from your app to Facebook or Twitter and so on... I would recommend to create a chooser to let the user pick which app from his phone he wants to user for sharing. It is simpler, more reliable and more the 'android way' of doing it.
Here is the code that you have to write :
Intent shareIntent=new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT,"I want to share this with you!");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Great Post");
startActivity(Intent.createChooser(shareIntent, "Share..."));
As for facebook and twitter, you can do this through their API. For facebook, fortunately they have provide android developer with facebook sdk for android, example included on the SDK.
And for Twitter you can use external libraries as written on twitter developer docs, and there is a library called Twitter4J that is android ready.
Unfortunately Google Plus API are not available yet.
Now you can try this library: https://github.com/antonkrasov/AndroidSocialNetworks
It's very easy to use:
mSocialNetworkManager = (SocialNetworkManager) getFragmentManager().findFragmentByTag(SOCIAL_NETWORK_TAG);
if (mSocialNetworkManager == null) {
mSocialNetworkManager = SocialNetworkManager.Builder.from(getActivity())
.twitter(<< TWITTER API TOKEN >>, << TWITTER API SECRET >>)
.linkedIn(<< LINKED_IN API TOKEN >>, << LINKED_IN API TOKEN >>, "r_basicprofile+rw_nus+r_network+w_messages")
.facebook()
.googlePlus()
.build();
getFragmentManager().beginTransaction().add(mSocialNetworkManager, SOCIAL_NETWORK_TAG).commit();
}
...
mSocialNetworkManager.getTwitterSocialNetwork().requestLogin(new OnLoginCompleteListener() {
#Override
public void onLoginSuccess(int socialNetworkID) {
}
#Override
public void onError(int socialNetworkID, String requestID, String errorMessage, Object data) {
}
});
In your app you can use Fabric IDE plugins to integrate your app with twitter.
With Fabric you can integrate twitter in simple steps
The Fabric IDE plugins will automatically create and configure a Twitter application when you use it to integrate the Twitter Kit into your app.
You can read related documentation on below link-
https://docs.fabric.io/android/index.html