I’ve seen a lot of confusion about how to use Intents within an application. To help developers out, I present a tutorial:
How to use Intents to invoke your own Activity, Broadcast Receiver, or Service
- Let’s say you’ve already written an Activity, named “MapActivity.” Declare that Activity in AndroidManifest.xml:
Replace “Activity” with “Receiver” or “Service”, as necessary.
Notice how there isn’t an Intent filter? That’s because you don’t need one! Only declare an Intent filter if you want other applications to be able to invoke your Activity/BroadcastReceiver/Service.
- Create a new Intent in the place where you want to open your Activity/Receiver/Service:
ComponentName comp =
Intent intent = new Intent();
This creates a new Intent for the class named package.name.MapActivity…in other words, the class named MapActivity in the “package.name” namespace.
Notice how I didn’t set an action string? That’s because you don’t need to! If you set an action string, other applications could register to receive your Intent, so it would get delivered to the wrong place.
- Send the Intent:
(Or sendBroadcast or startService, depending on the type of component you’re trying to invoke.)
Lots of developers try to do this using Intent Filters and action strings, and end up with security bugs. Don’t make their mistake! If you set a component name like I showed above, you’ll know that (1) your Intent will always get delivered to the right place, and (2) other apps can’t unexpectedly open up your Activity/Receiver/Service.
If you’re interested in reading more about this topic, Erika Chin and I wrote a MobiSys paper about common Intent errors. In particular, check out Sections 3 and 5.2. Section 3 talks about the types of security vulnerabilities that can occur with Intents, and Section 5.2 gives examples of vulnerabilities we found in real-world applications.