{"id":19088,"date":"2015-04-19T23:32:36","date_gmt":"2015-04-19T18:02:36","guid":{"rendered":"http:\/\/www.tothenew.com\/blog\/?p=19088"},"modified":"2015-04-19T23:32:36","modified_gmt":"2015-04-19T18:02:36","slug":"using-google-cloud-platform-in-an-android-app","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/using-google-cloud-platform-in-an-android-app\/","title":{"rendered":"Using Google Cloud Platform  in an Android App"},"content":{"rendered":"<p>Hi<br \/>\nThis 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&#8217;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 .<br \/>\nThe project:This  project consists of all the details of how many users there are, billing etc .<br \/>\nBucket: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 .<br \/>\nObjects: 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<br \/>\nThe data can be accesed using JSON\/XML  .<\/p>\n<p>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 .<br \/>\nAuthentication:<br \/>\nIn order  to authentication we will  use  standard Google pattern<br \/>\n1)Registering our application: The details can be found here (https:\/\/developer.android.com\/google\/auth\/http-auth.html)<br \/>\n2) Invoking the account picker dialog<br \/>\n[code language=&#8221;java&#8221;]<br \/>\nstatic final int REQUEST_CODE_PICK_ACCOUNT = 1000;<br \/>\nprivate void pickUserAccount() {<br \/>\n\u00a0 \u00a0 String[] accountTypes = new String[]{&quot;com.google&quot;};<br \/>\n\u00a0 \u00a0 Intent intent = AccountPicker.newChooseAccountIntent(null, null,<br \/>\n\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 accountTypes, false, null, null, null, null);<br \/>\n\u00a0 \u00a0 startActivityForResult(intent, REQUEST_CODE_PICK_ACCOUNT);<br \/>\n}<\/p>\n<p>3)Retrieving the account name<br \/>\nString mEmail; \/\/ Received from newChooseAccountIntent(); passed to getToken()<\/p>\n<p>@Override<br \/>\nprotected void onActivityResult(int requestCode, int resultCode, Intent data) {<br \/>\n\u00a0 \u00a0 if (requestCode == REQUEST_CODE_PICK_ACCOUNT) {<br \/>\n\u00a0 \u00a0 \u00a0 \u00a0 \/\/ Receiving a result from the AccountPicker<br \/>\n\u00a0 \u00a0 \u00a0 \u00a0 if (resultCode == RESULT_OK) {<br \/>\n\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 mEmail = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);<br \/>\n\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \/\/ With the account name acquired, go get the auth token<br \/>\n\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 getUsername();<br \/>\n\u00a0 \u00a0 \u00a0 \u00a0 } else if (resultCode == RESULT_CANCELED) {<br \/>\n\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \/\/ The account picker dialog closed without selecting an account.<br \/>\n\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \/\/ Notify users that they must pick an account to proceed.<br \/>\n\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 Toast.makeText(this, R.string.pick_account, Toast.LENGTH_SHORT).show();<br \/>\n\u00a0 \u00a0 \u00a0 \u00a0 }<br \/>\n\u00a0 \u00a0 }<br \/>\n\u00a0 \u00a0 \/\/ Later, more code will go here to handle the result from some exceptions&#8230;<br \/>\n}<br \/>\n[\/code]<br \/>\nThis 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 .<br \/>\n[code language=&#8221;java&#8221;]<br \/>\n   @Override<br \/>\n\u00a0 \u00a0 protected Void doInBackground(Void&#8230; params) {<br \/>\n\u00a0 \u00a0 \u00a0 \u00a0 try {<br \/>\n\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 String token = fetchToken();<br \/>\n\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 if (token != null) {<br \/>\n\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \/\/ Insert the good stuff here.<br \/>\n\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \/\/ Use the token to access the user&#8217;s Google data.<br \/>\n                \/\/We have stored the token in our singleton for future use<br \/>\n\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 }<br \/>\n\u00a0 \u00a0 \u00a0 \u00a0 } catch (IOException e) {<br \/>\n\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \/\/ The fetchToken() method handles Google-specific exceptions,<br \/>\n\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \/\/ so this indicates something went wrong at a higher level.<br \/>\n\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \/\/ TIP: Check for network connectivity before starting the AsyncTask.<br \/>\n\u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 &#8230;<br \/>\n\u00a0 \u00a0 \u00a0 \u00a0 }<br \/>\n\u00a0 \u00a0 \u00a0 \u00a0 return null;<br \/>\n\u00a0 \u00a0 }<\/p>\n<p>\u00a0 \u00a0 \/**<br \/>\n\u00a0 \u00a0 \u00a0* Gets an authentication token from Google and handles any<br \/>\n\u00a0 \u00a0 \u00a0* GoogleAuthException that may occur.<br \/>\n\u00a0 \u00a0 \u00a0*\/<br \/>\n\u00a0 \u00a0protected String fetchToken() throws IOException {<br \/>\n        try {<br \/>\n                       return GoogleAuthUtil.getToken(mActivity, mEmail,&quot;oauth2:&quot;+ StorageScopes.DEVSTORAGE_FULL_CONTROL);<br \/>\n        } catch (UserRecoverableAuthException userRecoverableException) {<br \/>\n            \/\/ GooglePlayServices.apk is either old, disabled, or not present<br \/>\n            \/\/ so we need to show the user some UI in the activity to recover.<br \/>\n            ((MainActivity) mActivity).handleException(userRecoverableException);<br \/>\n            Log.i(&quot;UserRecoverableAuthException&quot;, userRecoverableException.getMessage());<br \/>\n        } catch (GoogleAuthException fatalException) {<br \/>\n            \/\/ Some other type of unrecoverable exception has occurred.<br \/>\n            \/\/ Report and log the error as appropriate for your app.<br \/>\n            Log.i(&quot;GoogleAuthException&quot;, fatalException.getMessage());<\/p>\n<p>        }<br \/>\n        return null;<br \/>\n    }<br \/>\n\u00a0 \u00a0[\/code]<br \/>\nThis 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 &#8220;oauth2&#8243;: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 :<br \/>\n[code language=&#8221;java&#8221;]<br \/>\nprivate static Storage getStorage() throws Exception {<br \/>\n        if (storage == null) {<br \/>\n            HttpTransport httpTransport = new NetHttpTransport();<br \/>\n            JsonFactory jsonFactory = new JacksonFactory();<br \/>\n           List&lt;String&gt; scopes = new ArrayList&lt;String&gt;();<br \/>\n            scopes.add(StorageScopes.DEVSTORAGE_FULL_CONTROL);<br \/>\n           GoogleCredential credential = new GoogleCredential().setAccessToken(MySingleton.getMyInstance().getauthtoken());<br \/>\n          MySingleton.getMyInstance().setSingleCred(credential);<br \/>\n          storage = new Storage.Builder(httpTransport, jsonFactory,credential).setApplicationName(APPLICATION_NAME_PROPERTY).build();<br \/>\n        }<br \/>\n        return storage;<br \/>\n    }<br \/>\n[\/code]<br \/>\nThe details of the java method can be found here :<br \/>\n(https:\/\/github.com\/pliablematter\/simple-cloud-storage\/blob\/master\/src\/main\/java\/com\/pliablematter\/cloudstorage\/CloudStorage.java)<br \/>\nThe details of the android project can be found here :<br \/>\n(https:\/\/github.com\/salilkaul\/SampleApp)<\/p>\n","protected":false},"excerpt":{"rendered":"<p>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&#8217;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 [&hellip;]<\/p>\n","protected":false},"author":151,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":3},"categories":[1],"tags":[],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/19088"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/151"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=19088"}],"version-history":[{"count":0,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/19088\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=19088"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=19088"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=19088"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}