Here's a follow up on my Google IO 2012 talk on building awesome Android Apps using Google Cloud Endpoints. You can sign up for the Google Cloud Endpoints Trusted Tester program and try this out!
Google Cloud Endpoints allows you to define business logic on App Engine and access them via RESTful or RPC APIs on multiple platforms including Android, IOS and JavaScript. Cloud Endpoints are built using Google’s API infrastructure, which means that you get all the benefits of Google APIs (Google+ API, GMail API etc):
- Built-in authentication support
- APIs Console to manage your APIs
- APIs Explorer to discover and try out your APIs on a browser
- Automatically generated client libraries for Android, IOS and JavaScript
The Google Plugin for Eclipse (GPE) allows you to create and easily consume Cloud Endpoints. GPE provides the following features to help you develop Cloud Endpoints:
- Automatic generation of an Endpoint class that contains code to create, get, list, update and delete your entity class - an entity class is just a POJO with JPA/JDO persistence annotations.
- Automatic generation of API configuration.
GPE provides the following additional features for Cloud Endpoints for Android:
- Generation of an App Engine Backend project.
- Generation of a strongly typed client library for Android. GPE copies over the generated client library and their dependencies to the Android project.
- Support for Google Cloud Messaging (GCM). GCM allows your Endpoints to notify Android devices of changes to any API resources on the App Engine.
Get started with Cloud Endpoints by picking one or more of the following target platforms. Do note that you can use the same App Engine backend for one or more target platforms.
- Android
- IOS
- Javascript
Cloud Endpoints for Android
Prerequisites:- The latest Google Plugin for Eclipse (GPE)
- The latest Android Development Tools (This plugin is also available via the GPE install)
- Sign-up for the Cloud Endpoints Trusted Tester program.
Workflows:
- Creating an Android Application that uses Cloud Endpoints
- Adding Authentication to the Cloud Endpoints
- Using Google Cloud Messaging with Cloud Endpoints
Creating an Android Application that uses Cloud Endpoints
- Create an Android project using the ADT’s Android Application Wizard.
- Create an App Engine Backend project for the Android project.
- Create your Entity class (POJO) - this is a class that represents the Endpoint resource with a bunch of class attributes, setter and getter functions. You can add JPA annotations (@Entity, @Id etc) or JDO annotations to specify that this entity class needs to be persisted. As an example, here is a class representing a Note.
package com.cloudnotes;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Note {
@Id
private String id;
private String description;
private String emailAddress;
public Note() {
}
public String getId() {
return id;
}
public String getDescription() {
return description;
}
public String getEmailAddress() {
return emailAddress;
}
public void setId(String idIn) {
this.id = idIn;
}
public void setDescription(String description) {
this.description = description;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
}
- Generate the Endpoint class for each Entity class. This generates an Endpoint class that has the implementation for insert, update, remove, get, list methods on the Endpoint class using JPA or JDO as specified in the Entity class.
The @Api annotation indicates that this is an Endpoint class. You can modify this class as per your needs. To add additional methods, you will need to add the @ApiMethod annotations for these methods. Example: a searchNote(String note) method would have the annotation: @ApiMethod (httpMethod=”GET”, name=”note.search”)
Note:
- In the Endpoint methods, the return value type cannot be simple type such as String or int. The return value needs to be a POJO, an array or a Collection.
- The listXXX(), getXXX(id) are exposed as HTTP GETs, insertXXX(XXX) is exposed as a HTTP POST, updateXXX(XXX) is exposed as a HTTP PUT, and removeNote(Note) is exposed as a HTTP DELETE.
- Generate Cloud Endpoint Client Library for the App Engine project by right-clicking the App Engine project, and selecting Google > Generate Cloud Endpoint Client Library
- Modify your Android Application to call into your defined Endpoint. You can write a class that extends the Android AsyncTask to make sure that the network call to the Endpoint does not block any UI thread.
The following code snippet shows how you can call into Noteendpoint.insertNote()
Builder endpointBuilder = new Noteendpoint.Builder(
AndroidHttp.newCompatibleTransport(),
new JacksonFactory(),
new HttpRequestInitializer() {
public void initialize(HttpRequest httpRequest) { }
});
Noteendpoint endpoint = CloudEndpointUtils.updateBuilder(
Note: Android authentication code shown here requires the google-play-services.jar file to be included in your libs/ folder. This JAR file has not yet been released. I will update this blog once the JAR file is released.
@Api(name = "noteendpoint",
To specify the credential while creating a handle to the Endpoint:
endpointBuilder).build();
try {
Note result = endpoint.insertNote(note).execute();
} catch (IOException e) {
//Handle exception
}
- Test Cloud Endpoints in the local environment.
- Run App Engine local development server for testing. Hit the Run button on the App Engine application to start the local development server.
- In your Android project, set CloudEndpointUtils.LOCAL_ANDROID_RUN to true. This indicates that the Android application connects to the local development server.
- Run your Android application in your emulator.
- Test Cloud Endpoints with App Engine.
- Set the Application ID for the App Engine project.
- Deploy the App Engine project to App Engine.
- In your Android project within the CloudEndpoints class, set LOCAL_ANDROID_RUN to false. This indicates that the Android application connects to the remote App Engine app.
- Run your Android application in your emulator.
Adding Authentication to the Cloud Endpoints
Cloud Endpoints can be authenticated with Google Accounts using OAuth 2.0. This allows your Endpoint to verify and know the identity of the authenticated user. The following steps will help you add Authentication to your Cloud Endpoints.Note: Android authentication code shown here requires the google-play-services.jar file to be included in your libs/ folder. This JAR file has not yet been released. I will update this blog once the JAR file is released.
- Register a client ID in the Google APIs Console for your Android application
- Register an App Engine App ID.
- In the Endpoint class, under the @Api annotation (or the @ApiMethod annotation), set the registered Client ID the “clientIds” attribute, and the App Engine App ID as the “audience” attribute. The following code snippet shows this:
@Api(name = "noteendpoint",
clientIds = {"7232929396-4d7boi9meg5qmir9q80eg048qfval6rc.apps.googleusercontent.com
"},
audiences = {"cloudnotes2012.appspot.com"})
public class NoteEndpoint {...}
- Modify your methods to take in a User object (com.google.appengine.api.users.User) as an additional parameter. For an authenticated call, App Engine automatically fills in this attribute with the logged on user. The following code shows adding a User parameter to the listNote() method.
public List<Note> listNote(User user) {...}
To fetch a GoogleAccountCredential instance:
- Modify your methods to modify the Datastore queries to query by the logged in User’s email address. The following code snippet shows querying for Notes for a given User.
Query query = mgr.createQuery("select n from Note n where n.emailAddress = :emailAddress");
query.setParameter("emailAddress", user.getEmail());
- GoogleAccountCredential.java allows you to manage Google Account selection and authorization of Google Accounts on the Android Application. You can modify your Android Application to use GoogleAccountCredential to get a handle to the Endpoint.
To fetch a GoogleAccountCredential instance:
GoogleAccountCredential credential = GoogleAccountCredential.usingAudience(
context, audience);
where:
context is the Android Application Context
audience is the App Engine App ID (eg:cloudnotes2012.appspot.com)
To specify the credential while creating a handle to the Endpoint:
Builder endpointBuilder = new Noteendpoint.Builder(
AndroidHttp.newCompatibleTransport(),
new JacksonFactory(),
credential);
Noteendpoint endpoint = CloudEndpointUtils.updateBuilder(
For example, let’s say a user uses a Note application from 2 devices: Device A and Device B. If the user is adding a note from Device A. Google Cloud Messaging can be used in the Cloud Endpoint for the insert operation to ping Device B to indicate that a note has been added.
You can perform the following steps to use Google Cloud Messaging with Cloud Endpoints.
DevicePing.pingAllDevices(user.getEmail() + ":" + note.getId() + ":insert");
Java Codelab
endpointBuilder).build();
Using Google Cloud Messaging with Cloud Endpoints
Google Cloud Messaging allows your Cloud Endpoints to send notifications to registered Android devices whenever the state of a resource changes.For example, let’s say a user uses a Note application from 2 devices: Device A and Device B. If the user is adding a note from Device A. Google Cloud Messaging can be used in the Cloud Endpoint for the insert operation to ping Device B to indicate that a note has been added.
You can perform the following steps to use Google Cloud Messaging with Cloud Endpoints.
- In the Google APIs Console, enable Google Cloud Messaging
- In the Google APIs Console, create a server API key. This will help App Engine securely communicate with the Google Cloud Messaging Server.
- In the App Engine project, DevicePing.java is a helper class that allows you to ping all registered devices. You should update DevicePing.API_KEY to specify the API key obtained in the previous step.
- In the App Engine project, you can modify the generated Endpoint class to send pings to registered devices. The following code snippet can be inserted in the insertNote(Note) method to send a ping to all registered devices.
DevicePing.pingAllDevices(user.getEmail() + ":" + note.getId() + ":insert");
- In the Android project, GCMIntentService.java is a helper class that helps register the device and perform actions when a message is received from the Google Cloud Messaging Server.
- Specify the Google APIs Project ID in GCMIntentService.java in the PROJECT_ID field. The Project ID can be obtained from the URL to the API console project. Example: https://code.google.com/apis/console/?pli=1#project:<PROJECT_ID>:services
- Modify GCMIntentService.onMessage() to handle the incoming GCM notification.
- In your Android project, call GCMIntentService.register(..) from your application (eg: onCreate() of your activity) to register the device with the Google Cloud Messaging Server and App Engine.
I/O Overview Talks
Java Codelab
Appendix
Source Code for GoogleAccountCredential.java
import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.TransientAuthException;
import com.google.android.gms.common.AccountPicker;
import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager;
import com.google.api.client.http.BackOffPolicy;
import com.google.api.client.http.ExponentialBackOffPolicy;
import com.google.api.client.http.HttpExecuteInterceptor;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpUnsuccessfulResponseHandler;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import android.accounts.Account;
import android.content.Context;
import android.content.Intent;
import java.io.IOException;
/**
* Manages account selection and authorization for Google accounts.
*/
public final class GoogleAccountCredential implements HttpRequestInitializer {
final Context context;
final String scope;
private String accountName;
private final GoogleAccountManager accountManager;
private Account account;
/**
* @param context context
* @param scope scope to use on {@link GoogleAuthUtil#authenticate}
*/
private GoogleAccountCredential(Context context, String scope) {
accountManager = new GoogleAccountManager(context);
this.context = context;
this.scope = scope;
}
/**
* Constructor a new instance using OAuth 2.0 scopes.
*
* @param context context
* @param scopes OAuth 2.0 scopes
* @return new instance
*/
public static GoogleAccountCredential usingOAuth2(Context context, String... scopes) {
Preconditions.checkArgument(scopes.length != 0);
String scope = "oauth2:" + Joiner.on(' ').join(scopes);
return new GoogleAccountCredential(context, scope);
}
/** Sets the audience scope to use with Google Cloud Endpoints. */
public static GoogleAccountCredential usingAudience(Context context, String audience) {
Preconditions.checkArgument(audience.length() != 0);
String scope = "audience:" + audience;
return new GoogleAccountCredential(context, scope);
}
/**
* Sets the selected Google account name (e-mail address), for example {@code "johndoe@gmail.com"}
* , or {@code null} for none.
*/
public GoogleAccountCredential setAccountName(String accountName) {
this.accountName = accountName;
account = accountManager.getAccountByName(accountName);
return this;
}
public void initialize(HttpRequest request) {
RequestHandler handler = new RequestHandler();
request.setInterceptor(handler);
request.setUnsuccessfulResponseHandler(handler);
request.setBackOffPolicy(new ExponentialBackOffPolicy());
}
/**
* Returns the selected Google account name (e-mail address), for example
* {@code "johndoe@gmail.com"}, or {@code null} for none.
*/
public String getAccountName() {
return accountName;
}
/** Returns the selected Google account or {@code null} for none. */
public Account getAccount() {
return account;
}
/** Returns all Google accounts or {@code null} for none. */
public Account[] getAllAccounts() {
return accountManager.getAccounts();
}
/**
* Returns an intent to show the user to select a Google account, or create a new one if there are
* none on the device yet.
*
* <p>
* Must be run from the main UI thread.
* </p>
*/
public Intent newChooseAccountIntent() {
return AccountPicker.newChooseAccountIntent(account,
null,
new String[] {GoogleAccountManager.ACCOUNT_TYPE},
true,
null,
null,
null,
null);
}
/**
* Returns an OAuth 2.0 access token.
*
* <p>
* Must be run from a background thread, not the main UI thread.
* </p>
*/
public String getToken() throws IOException {
BackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
while (true) {
try {
try {
return GoogleAuthUtil.getToken(context, accountName, scope);
} catch (TransientAuthException e) {
// network or server error, so retry use
long backOffMillis = backOffPolicy.getNextBackOffMillis();
if (backOffMillis == BackOffPolicy.STOP) {
throw e;
}
// sleep
try {
Thread.sleep(backOffMillis);
} catch (InterruptedException e2) {
// ignore
}
}
} catch (GoogleAuthException exception) {
IOException io = new IOException();
io.initCause(exception);
throw io;
}
}
}
class RequestHandler implements HttpExecuteInterceptor, HttpUnsuccessfulResponseHandler {
/** Whether we've received a 401 error code indicating the token is invalid. */
boolean received401;
String token;
public void intercept(HttpRequest request) throws IOException {
token = getToken();
request.getHeaders().setAuthorization("Bearer " + token);
}
public boolean handleResponse(
HttpRequest request, HttpResponse response, boolean supportsRetry) {
if (response.getStatusCode() == 401 && !received401) {
received401 = true;
GoogleAuthUtil.invalidateToken(context, token);
return true;
}
return false;
}
}
}
This comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
ReplyDeletealso...
ReplyDelete"Modify your Android Application to call into your defined Endpoint. "
do you have a simple example of this? A class file would be a huge help.
Here's a simple example of such a class. It extends AsyncTask to do the networking off the UI thread.
DeleteNoteendpointAsyncTask.class
This comment has been removed by the author.
DeleteI haven't been accepted to the endpoints trusted testers. Acutally I try to run this example on my local machine.
ReplyDeleteCan I provide an OAuth2 Request for my local app using GoogleAccountCredential.usingAudience(...) ?
Can I use Google Cloud Messaging for Android on my local machine? How do I register a device to the Google Cloud Messaging for Android? Is it possible at all on localhost?
I've already registered my GoogleAccunt and my Appengine Projekt for the Cloud Messaging.
I'm so excited of the possibilites of cloudendpoints. Help would be really awesome!
Thanks for this tutorial! Do you have any other resource about this topic? additional tutorials and code examples will be great!
ReplyDeleteThank you for this tutorial ~
ReplyDeleteThank you!
ReplyDeleteIt will be very nice if you can share the complete project to download and get it exactly right.
Thank you!!
This comment has been removed by the author.
ReplyDeleteNET is a Programme Several important part of what Windows is running in Run On A Present For General klike program. Cloud Development This Cool People What do I need It. NET application that runs the computer That arrogant. For those who developed, .NET development, ASP development, SharePoint development, Microsoft development , software development, Singapore – Total eBiz Solutions Home
ReplyDelete
ReplyDeleteThanks for this post it's really interesting all type of art work are done by iPhone.
Very nice, keep it up.
--------------------------------------------------------------------------------------------------------------
iPhone App Development & iOS App Development & Android Application Development
-------------------------------------------------------------------------------------------------
iPhone 5 App Development & iPad Application Developer
Google was not intrigued by helping engineers profit from their applications. They essentially needed a stage to control. So they made improvement on it as cool and synergistic as conceivable. The neighborhood of engineers helped a ton. Then again, Apple was genuine about offering applications and profiting from them. So they put resources into the application dispersion chain.
ReplyDeleteAndriod Application Development // iPhone Application Development // Mobile Application Development
Thanks for sharing this post. There are many Android Game applications in the market and OnGraph Technologies is the best Android Game Development Company in India always tried to launch new apps.
ReplyDeleteThanks for this publish it's really exciting all kind of art perform are done by iPhone.Very awesome, keep it up. Cloud inventory management
ReplyDeleteGreat Information Thanks For Sharing
ReplyDeleteFor More Information You Can Visit This Website Web Application Development Solutions
These are some of the common web application development solutions we provide Web 2.0, Community and Networking Applications Effective and easy-to-use user.
ReplyDeleteWeb Application Development
IPhone Application development and programming always require innovative thinking and in-depth technological knowledge.
ReplyDeleteiPhone Application Development
Thanks so very much for taking your time to create this very useful and informative site. I have learned a lot from your site. Thanks!!
ReplyDeleteJAVA Training Center in Chennai
iphone app development and androids applications when created, developers always require innovative thoughts in mind and in-depth technological knowledge.
ReplyDeleteI am getting problem while creating new entity. It is not getting shown in app engine.Please help me
ReplyDeleteSuperbly written article, if only all bloggers offered the same content as you,
ReplyDeletefacetime for android
Awesome Post - Building Awesome Android Apps with Google Cloud Endpoints
ReplyDeleteThanks for sharing this infos...
ReplyDeleteWeb-Design Deutschland und Web Development -Unternehmen in Deutschland E-Commerce- Website -Entwicklung, Web-Site -Design , Flash- Website usw. besuchen Sie uns @ http://www.accuratesolutionsltd.com/e-commerce-entwicklung/
ReplyDeleteI have always known that developing application is a complex task that requires excellent computational and programming skills but this article has proved my ideology to be wrong. I am now familiar with the process of developing an application and I am looking forward to reading more articles from this site. Check out this professional writing site, Guidance with Quantitative Research Paper, I found it to be offering credible writing services.
ReplyDeleteIt is secure to save data using cloud technology for any android device. nice post with more informative details.
ReplyDeleteAndroid Web Development
Keep sharing.!!
Hey, very nice site. I came across this on Google, and I am stoked that I did. I will definitely be coming back here more often. Wish I could add to the conversation and bring a bit more to the table, but am just taking in as much info as I can at the moment. Thanks for sharing.
ReplyDeleteMobile Application Development
If looking to develop an awesome andorid app it's highly recommend to go with reputed app developers in Dubai not just every one.
ReplyDeleteThat’s a great blog!.
ReplyDeleteFor VoIP Dialers, Web based chat, WebRTC development, Digital Marketing and Social Media just try visiting our site!
Software Development Company
VoIP Dialer Development
If you are looking to game interface design our outsource graphic design company is company is ready to take your project!
ReplyDeleteIf looking to develop an awesome andorid app it's highly recommend to go with reputed app developers in Dubai not just every one.
ReplyDeleteoutsourcingall.com is a Porn Training site. outsourcingall.com is the largest Amateur porn training institute with the hottest selection Online and offline real life cam.
ReplyDeletefree bangla sex video dhaka
You have Top companies listed well in India. I will strongly accommodate the one company. The Company Name is Freelance To India Which provide the top quality services in Website and Mobile Application Development.
ReplyDeleteIndeed, apps with great designs are a joy to use. You have a good method for build android apps. People prioritize those apps that use new system features as well reflect the latest visual styles. Blogger can also write for us about android apps.
ReplyDeleteGreat post you have there. It has enlightened me and added knowledge about the subject. You can also look at help with SPSS analysis .
ReplyDeleteThanks for sharing your knowledge with us. I really liked your post. You shared a detailed post about android apps. After reading this post we can easily understand about mobile apps. Great work. Get help from dissertation writing services , a distinctive writing company UK.
ReplyDeleteHIPAA Security officer Training will help in understanding the administrative, physical and technical safeguards for keeping PHI safe specifically in electronic form (computers, networks, email, software, electronic transmissions, etc.) from ransomware, disasters, hackers, and electronic theft.
ReplyDeleteThis comment has been removed by the author.
ReplyDeletethanks for sharing useful information about Building Awesome Android Apps with Google Cloud Endpoints.
ReplyDeletewe are leading mobile app development companies in dubai and offer best mobile app development services.
Thanks for sharing such amazing & informative post here. I really liked it very much.
ReplyDeleteI also like to suggest you the best custom software development company in Singapore, You can go with Genic Solutions for inventory management software. Get in touch ASAP to get the best quotes.
Thanks
Nice Blog!
ReplyDeleteFacing error while using QuickBooks get instant solution with our QuickBooks experts.Dial +1-855-533-6333 QuickBooks Enterprise Support Phone Number
Really its very useful information that you have shared and thanks for sharing the information with us.
ReplyDeleteBest Web Development Company US
This comment has been removed by the author.
ReplyDeleteThanks for posting this info. I just want to let you know that I just check out your site tommy egan bomber jacket
ReplyDeleteAmazing site you have here.playboyclothing
ReplyDeleteI feel extremely cheerful to have seen your post. I found the most beautiful and fascinating one. I am really extremely glad to visit your post MillionMerch.
ReplyDelete
ReplyDeleteThanks for sharing this premium article free of cost i really like your article . you can also shop here
shop street wear
https://liltjaymerch.net/
ReplyDeleteNice and interesting post,Ihttps://theboyfriendjeans.com/ appreciate your hard work,keep uploading more, Thank you for sharing valuable information.
ReplyDeleteI read this article.https://quackitymerch.net/ I think You put a great deal of exertion to make this article.
ReplyDeleteThis is a very nice blog and learned more knowledge.https://drewhouseofficial.com/hoodies/
ReplyDeleteThanks for sharing such beautiful information with us. We are waiting for some more info if you shared with us. https://fmerchandise.com/
ReplyDeleteNice blog and absolutely outstanding.Click HereYou can do something much better but I still say this is perfect. Keep trying for the best.
ReplyDeleteCMOLDS is one of the leading web development companies dubai offering web and app development companies specializing in this domain.
ReplyDeleteThis comment has been removed by the author.
ReplyDelete1. Minimalist Aesthetic with Functional Appeal
ReplyDeleteMinus Two is known for its minimalist design philosophy, and their cargo pants are a perfect reflection of this. Unlike traditional cargo pants, which often have a bulky appearance, Minus Two has created a more streamlined and sleek version of the cargo pant. They maintain the functional elements—such as multiple pockets—but with a refined and minimalist touch that makes them look modern and sophisticated. minus two