Using Google Cloud Platform in an Android App
Hi
This article is regarding how to use the Google cloud API from an android device . Google Cloud Storage is an Internet service to store data in Google’s cloud. . By integrating this service with our Android application we can provide a good level of security to our data since the data will not be stored on the SD card but on the Google cloud . So our application will consist basically of two parts the front end which will be used to generate the content which is downloaded and upload the content and the back end will be the Google cloud Storage . To give a brief overview of the google cloud it consists of the following major parts .
The project:This project consists of all the details of how many users there are, billing etc .
Bucket:This is the logical unit in which the data is saved .The main things to be kept in mind is that buckets cannot be nested . They are like folders at the topmost level . They are used to organize data and provide access control to data. They cant be shared among buckets .
Objects: They are the actual data that is stored in the cloud . This consists basically of the data about the object itself and meta data about the object stored in the form of key value pairs
The data can be accesed using JSON/XML .
Android Front End: The application will consist mainly of two components . The UI parts which will be used to generate/consume content . We will provide the ability to upload images from the gallery or from the camera . The other feature we will use is to download the the data present in out bucket . The other part is authenticating with the google cloud api and the actual upload/download of data .
Authentication:
In order to authentication we will use standard Google pattern
1)Registering our application: The details can be found here (https://developer.android.com/google/auth/http-auth.html)
2) Invoking the account picker dialog
[code language=”java”]
static final int REQUEST_CODE_PICK_ACCOUNT = 1000;
private void pickUserAccount() {
String[] accountTypes = new String[]{"com.google"};
Intent intent = AccountPicker.newChooseAccountIntent(null, null,
accountTypes, false, null, null, null, null);
startActivityForResult(intent, REQUEST_CODE_PICK_ACCOUNT);
}
3)Retrieving the account name
String mEmail; // Received from newChooseAccountIntent(); passed to getToken()
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_PICK_ACCOUNT) {
// Receiving a result from the AccountPicker
if (resultCode == RESULT_OK) {
mEmail = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
// With the account name acquired, go get the auth token
getUsername();
} else if (resultCode == RESULT_CANCELED) {
// The account picker dialog closed without selecting an account.
// Notify users that they must pick an account to proceed.
Toast.makeText(this, R.string.pick_account, Toast.LENGTH_SHORT).show();
}
}
// Later, more code will go here to handle the result from some exceptions…
}
[/code]
This email name will be passed to GoogleAuthUtil.getToken() . This is network call so should be done in a separate worker thread . We will make use of an async task .
[code language=”java”]
@Override
protected Void doInBackground(Void… params) {
try {
String token = fetchToken();
if (token != null) {
// Insert the good stuff here.
// Use the token to access the user’s Google data.
//We have stored the token in our singleton for future use
}
} catch (IOException e) {
// The fetchToken() method handles Google-specific exceptions,
// so this indicates something went wrong at a higher level.
// TIP: Check for network connectivity before starting the AsyncTask.
…
}
return null;
}
/**
* Gets an authentication token from Google and handles any
* GoogleAuthException that may occur.
*/
protected String fetchToken() throws IOException {
try {
return GoogleAuthUtil.getToken(mActivity, mEmail,"oauth2:"+ StorageScopes.DEVSTORAGE_FULL_CONTROL);
} catch (UserRecoverableAuthException userRecoverableException) {
// GooglePlayServices.apk is either old, disabled, or not present
// so we need to show the user some UI in the activity to recover.
((MainActivity) mActivity).handleException(userRecoverableException);
Log.i("UserRecoverableAuthException", userRecoverableException.getMessage());
} catch (GoogleAuthException fatalException) {
// Some other type of unrecoverable exception has occurred.
// Report and log the error as appropriate for your app.
Log.i("GoogleAuthException", fatalException.getMessage());
}
return null;
}
[/code]
This method will return the token which we will use . We can store the token in a Singleton class so that it can be used throughout the application .Please note that the scope passed is “oauth2″:StorageScopes.DEVSTORAGE_FULL_CONTROL . The other critical component is the code used to perform CRUD buckets/objects in our project . The main method is bellow . This returns the storage object which is used to perform the CRUD operations :
[code language=”java”]
private static Storage getStorage() throws Exception {
if (storage == null) {
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
List<String> scopes = new ArrayList<String>();
scopes.add(StorageScopes.DEVSTORAGE_FULL_CONTROL);
GoogleCredential credential = new GoogleCredential().setAccessToken(MySingleton.getMyInstance().getauthtoken());
MySingleton.getMyInstance().setSingleCred(credential);
storage = new Storage.Builder(httpTransport, jsonFactory,credential).setApplicationName(APPLICATION_NAME_PROPERTY).build();
}
return storage;
}
[/code]
The details of the java method can be found here :
(https://github.com/pliablematter/simple-cloud-storage/blob/master/src/main/java/com/pliablematter/cloudstorage/CloudStorage.java)
The details of the android project can be found here :
(https://github.com/salilkaul/SampleApp)
Very-Ultra helpful, thanks