Random thoughts, musings, and tech stuff

07 Nov 2015, 09:37

Share

This is the first post in a series about sharing information between apps. It will start with the basics, and move on to discuss how we might leverage this to do some interesting things. Additionally, I’ll be providing videos that cover the text contents of these posts (plus insightful things), so if you want to watch instead of read, check out the video below:

Series Table of Contents

Sharing in Android

In Android, information is shared between apps in few different ways, there’s local files stored in the shared storage area of the device, then there are Content Providers, and Intents. Using local files as information sharing seems pretty hacky, and is wide open for attack, so I’m not going to discuss that. Content Providers are interesting, but this series is going to be discussing Intents. If this goes well, maybe I’ll circle back and cover Content Providers.

Prerequisites

Launch an Activity

Let’s say that you want to open one Activity from another Activity, you’d use an intent like the following:

startActivity(new Intent(this, ActivityTwo.class));

In this example, the ‘information’ that you’re sharing is simply that you’d like ActivityTwo to appear on top of ActivityOne. If you’d like to see a fully working example of this, check this tag on GitHub.

(Quick side-note here, if you want to check out the repository at this step, first check out the repo, then run the following command: git checkout -b step1 step1. That will get you a branch at the step1 tag.)

That’s really it for the first example. You can run it on your device, and should see something like the following:

In the above example, the ‘LAUNCH INTENT’ button runs the startActivity code described above to launch the second activity.

Launch an Activity with Extras

Next, let’s extend the first example, and add a button to ActivityTwo that points back at ActivityOne. However, instead of just launching ActivityOne, we’ll send back some data along with it, that ActivityOne will display. Here’s the tag on GitHub for this state. ( git checkout -b step2 step2 )

Send a Broadcast

Now, let’s take a look at how to send an intent to a BroadcastReceiver. It’s fairly straightforward, but one little note is that we should add an entry to the AndroidManifest.xml with our intent filter:

We need entries for our Services and Activities as well, but when we add an intent-filter it lets the system know what this receiver can handle. (This is our first public API!) Now, we can send a broadcast:

Conclusion

That’s it for right now, but you saw a couple of basic things here. We’re now launching an Activity as well as passing some data along. We also now have our first public API! What’s more, our API runs something in the background, and doesn’t bring up another screen. This is an important point that we’ll get into later on. Next, we’ll extend that to start offering something useful.