This backend template employs Google Cloud Endpoints to define a RESTful backend API from very simple annotations of the server-side Java code. Google Cloud Endpoints also provide automated Java object marshalling/unmarshalling to JSON, generation of strongly-typed client libraries that can be called from your Android app, built-in authentication support and so on.
To add the backend to your existing Android app from this backend template, open Android Studio (installation instructions) and navigate to "File → New Module..." or right-click on your project and choose "New → Module".
In the "New Module" that appears, choose "App Engine Java Endpoints Module".
Enter the module/package names for your new backend, and choose the "client" module in your project which contains your Android app. The client module will be set up to call your newly generated backend.
Module name which you've entered above (marked with red 1) will be used in your Android Studio project. Package name (marked with red 2) will be used for all classes imported from this template and (reversed) for Endpoints API namespace. In turn, Endpoints API namespace will be used to derive the name of the autogenerated Android client libraries, hence this ensures that the names of generated client libraries will match your package name.
As soon as the backend module is added to your project and Gradle sync finishes, a new run configuration with your backend's module name should be created:
Rebuild your project (via "Build → Rebuild Project") and launch this run configuration. It will invoke appengineRun
task in Gradle plug-in for App Engine, which in turn will start the local App Engine Java development server.
To ensure that your backend started successfully, navigate to http://localhost:8080. If everything went well, you should see the following page:
When you created a backend module, strongly-typed client libraries have been automatically generated for you. These client libraries are re-built together with your backend module. Furthermore, your Android app ("client") module has been set up to include compile dependencies to these generated client libraries, access internet and so on.
To start sending requests to the added Cloud Endpoints backend API, you can use the following code snippet. In particular, this snippet illustrates how to create an AsyncTask which makes the request to the backend and prints the incoming result string to a toast in a given context:
class EndpointsAsyncTask extends AsyncTask<Pair<Context, String>, Void, String> {
private MyApi myApiService;
private Context context;
public EndpointsAsyncTask() {
MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
@Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
// end options for devappserver
myApiService = builder.build();
}
@Override
protected String doInBackground(Pair<Context, String>... params) {
context = params[0].first;
String name = params[0].second;
try {
return myApiService.sayHi(name).execute().getData();
} catch (IOException e) {
return e.getMessage();
}
}
@Override
protected void onPostExecute(String result) {
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
}
To make the actual call, invoke this EndpointsAsyncTask
from one of your Android activities. For example, to execute it from MainActivity
class, add the following code snippet to MainActivity.onCreate
method:
new EndpointsAsyncTask().execute(new Pair<Context, String>(this, "Manfred"));
If you have granted the internet access permission to your AndroidManifest.xml
file, added compile dependencies to Android app's build.gradle
file, and added an EndpointsAsyncTask
invokation to one of your Android app activities as per steps above, you should be all set to test your backend locally!
First, launch your backend locally as described in section 1.1. and ensure that you can access it via http://localhost:8080. Then, change the run configuration back to your Android app and run the Android emulator.
If everything goes well, you should see the following toast in your app:
If your backend is working locally, you can deploy it to Google App Engine. To begin with, create a new project on Google Developers Console (or choose an existing project, if you have one already).
Note down the "Project ID" (in this case "android-app-backend") and switch back to Android Studio. In Android Studio, open
<backend>/src/main/webapp/WEB-INF/appengine-web.xml
file and change
<application>myApplicationId</application>
to contain your real Project ID (in this case, again, "android-app-backend"):
<application>android-app-backend</application>
If you have started the local Java development server in an earlier step, stop it by opening "Run" tool window (1), choosing your backend run session (2) and pressing the red "Stop" button (3).
Then, switch to the "Terminal" tab and execute ./gradlew backend:appengineUpdate
command:
If you are running this task for the first time, you will be prompted to sign-in with your Google Account. After choosing the account and signing-in, give permissions to Google App Engine's "appcfg" tool and copy-paste the generated key back into Terminal:
After you paste the key and hit Return, your backend will be deployed to App Engine and will be accessible live at https://<Project ID>.appspot.com. (In this example, the backend would be hosted at https://android-app-backend.appspot.com.)
Once you have deployed your backend to App Engine, you can connect your Android app to it by modifying EndpointsAsyncTask
class defined in section 2 above. In particular, replace the lines
MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
.setRootUrl("http://10.0.2.2:8080/_ah/api/") // 10.0.2.2 is localhost's IP address in Android emulator
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
@Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
with a single line
MyApi.Builder builder = new MyApi.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null);
At this point you should be all set to run your Android app in an emulator or on the physical device, and successfully communicate with your new App Engine backend!