Try Your Hand at the Dropbox API for Android

drop-box

For cloud and Android developers, Dropbox is a very handy service. It offers cloud storage and a nifty tool to sync data. One of Dropbox’s biggest advantages is that it is so simple and easy to use particularly the developer API provided. This allows developers to harness the power of the cloud effectively. This article will focus on the basics of the Dropbox API, and how to integrate it with your Android apps.

Before we get started, you need to set up Eclipse and the Android SDK on your system; there’s plenty of information about that on the Net, so I’ll skip it.
Setting up Dropbox access
Setting up the Dropbox access for your app is relatively easy and straightforward. First you have to go to the Apps page of your Dropbox account (https://www.dropbox.com/developers/apps) and then create a new app. Once it is created, you will get the app key and the app secret key. These are unique values to your app, and are used for authenticating the connection between Dropbox servers and your app, and hence should not be shared. Also note the type of access specified when you create your app. There are two types of access you can specify: DROPBOX, which allows your app to access your entire Dropbox folder, or APP FOLDER, which only allows your app to access the folder specifically created for your app. Now, let’s proceed to create a new Android project in your Eclipse environment.

Configuration
Once you have created your Android project in Eclipse, download the Dropbox SDK for Android from the Dropbox site (https://www.dropbox.com/developers/reference/sdk). Extract the files, and copy the contents of the lib folder into your Android project’s lib folder. You can use the DBRoulette sample project in the examples folder as reference while doing this. After copying the libraries, tweak the AndroidManifest.xml file so that your app has sufficient permissions to access the required resources. Add the following code to your Manifest file, under the application tag:

<activity
      android:name="com.dropbox.client2.android.AuthActivity"
      android:launchMode="singleTask"
      android:configChanges="orientation|keyboard">
      <intent-filter>
        <!-- Change this to be db- followed by your app key -->
        <data android:scheme="db-APP-KEY" />
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.BROWSABLE"/>
        <category android:name="android.intent.category.DEFAULT" />
      </intent-filter>
</activity>

Also, you must specify in your Manifest file that your application will need to access the Internet. Hence, add an INTERNET permission in the manifest section, as follows:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

Now, move on to authenticating the app.

Authentication
Before looking at the code, try and understand how the authentication takes place. You supply the app key, the secret app key and the access type, which you obtained during the creation of the app on the Dropbox page, to create a new session. Now, your app needs to be authorised through the official Dropbox mobile app or Dropbox mobile website. So, at this point, the user will be redirected to a page (Figure 1) that will request permission to access the user’s Dropbox. Once the user accepts the app request, you will have the user’s access token pair, which you can use to make various API calls. Once the app is authenticated, it will be redirected back to the activity it was executing before the authentication call. After control is returned, you must finish the authentication, binding the user’s access tokens to the current session. It is also important to store these tokens somewhere after you obtain them, because if you do not, then the app will need to be authorised by the user every time it is restarted.
Here is the code for the above-mentioned steps. The comments specify which parts of the code correspond to each step.

//Create a new Session
private DropboxAPI<AndroidAuthSession> auth;
private final static String akey="INSERT-ACCESS-KEY-HERE";
private final static String askey="INSERT-SECRET-ACCESS-KEY-HERE";
private final static AccessType atype=AccessType.APP_FOLDER;
//Change to AccessType.DROPBOX if you selected dropbox access type.
AppKeyPair appkeys = new AppKeyPair(akey, askey);
AndroidAuthSession session=new AndroidAuthSession(appkeys, atype);
auth=new DropboxAPI<AndroidAuthSession>(session);

//User accepting the request for permission.
auth.getSession().startAuthentication(MainActivity.this);

//Return to your app
@Override
protected void onResume() {
    	super.onResume();
    	if(auth.getSession().authenticationSuccessful()) {
    		try {
    			auth.getSession().finishAuthentication();
    			AccessTokenPair tok=auth.getSession().getAccessTokenPair();
    			storeKeys(tok.key, tok.secret); //store the user's tokens somewhere for reuse.
    		}catch(Exception e){Log.d("info", "error", e);}
    	  }    }

figure 1 - Authentication

figure 2 - Dropbox App

At this point, you should have the Dropbox API set up on your Android system, and your session should also be authenticated. If you have the user’s tokens stored somewhere, it is recommended that you start off this section by reinitialising the access keys, to avoid user reauthentication. You can do this by using the following lines of code:

AccessTokenPair access = getStoredKeys();
//retrieve the stored tokens.
auth.getSession().setAccessTokenPair(access);

Let’s now look at the most important part of the API— the file operations using Dropbox.

Uploading a file
You can simulate reading a file using the ByteInputArray to operate on the contents of a given string. Any file on your device may also be used, by specifying the path to the file. A call to the putFile method uploads the file to Dropbox. The code for uploading a file is shown below:

 String content="Hello World!!";
        	ByteArrayInputStream ip=new ByteArrayInputStream(content.getBytes());
        	Entry e1=auth.putFile("/test.txt", ip, content.length(), null, null);
Downloading a file
Downloading is simple—use the getFile method to download your file, and store it on your Android device. The code to download a file from Dropbox (the same one you just uploaded) is:

File f=new File(getFilesDir()+"/test.txt");
 if(!f.exists())
   		f.createNewFile();
 is=new FileOutputStream(f);
 DropboxFileInfo e1=auth.getFile("/test.txt", null, is, null);

Obtaining file metadata
This is arguably the most useful feature of Dropbox. Most applications work by making decisions based on the metadata of a given file. The Dropbox API provides a method called metadata, which returns information related to the file, like last modified, revision, path, etc. This information is handy when you want to use previous versions of the file, or when you need some form of version control. A sample use of the metadata method is as follows:

Entry meta = auth.metadata("/test.txt", 1, null, false, null);

Now, putting everything together, the complete code for the MainActivity.java of your Android project is available at: http://www.opensourceforu.com/article_source_code/march13/Dropbox_Android.zip.
Writing apps that use the Dropbox API is straightforward. The ease of use and flexibility of the API make it a great way to provide cloud support for your app. The API has support for many different platforms like Android, iOS, Python and Ruby, and also has many third-party APIs, which extend Dropbox support for most other platforms as well. When you face a problem using the API, a great resource to look at is the Dropbox Developers’ site, at https://www.dropbox.com/developers/start/, which has a detailed overview about the use of the API.

Finally, the Dropbox API for Android is a quick and powerful way of allowing your applications to take advantage of cloud storage. Android, being a prominent mobile development platform, needs tools to provide seamless integration with cloud services, and the Dropbox API does exactly this.

All published articles are released under Creative Commons Attribution-NonCommercial 3.0 Unported License, unless otherwise noted.
Open Source For You is powered by WordPress, which gladly sits on top of a CentOS-based LEMP stack.

Creative Commons License.