Custom Intents and Broadcasting with Receivers
Hey everyone,
Here’s an example that tries to satisfy “Warrior’s” request on sending custom intents and grabbing them with broadcast receivers. This example has two receivers and an android manifest file:
The First Receiver:
public class OutgoingReceiver extends BroadcastReceiver { public static final String CUSTOM_INTENT = "jason.wei.custom.intent.action.TEST"; @Override public void onReceive(Context context, Intent intent) { System.out.println("HIT OUTGOING"); Intent i = new Intent(); i.setAction(CUSTOM_INTENT); context.sendBroadcast(i); } }
The Second Receiver:
public class IncomingReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(OutgoingReceiver.CUSTOM_INTENT)) { System.out.println("GOT THE INTENT"); } } }
The Android Manifest:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="jason.wei.apps.androidtest" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <receiver android:name=".OutgoingReceiver" android:enabled="true"> <intent-filter> <action android:name="android.intent.action.PHONE_STATE"></action> </intent-filter> </receiver> <receiver android:name=".IncomingReceiver" android:enabled="true"> <intent-filter> <action android:name="jason.wei.custom.intent.action.TEST"></action> </intent-filter> </receiver> </application> <uses-sdk android:minSdkVersion="3" /> <uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission> </manifest>
So here’s a quick explanation of what’s going on in this code snippet. So notice that we first define our custom intent as:
public static final String CUSTOM_INTENT = "jason.wei.custom.intent.action.TEST";
This is the intent’s action (i.e. typically this would be something like android.intent.action.ACTION_VIEW) and you can think of this as our way of “tagging” the intent and characterizing it. Notice that you can also attach data and extras to this intent as usual (see https://thinkandroid.wordpress.com/2009/12/26/passing-info-between-activities/).
Now, in our manifest, our intent filter only allows for intents with actions “jason.wei.custom.intent.action.TEST” to be received and so technically we don’t even need to do the check in the IncomingReceiver (but it never hurts).
The flow of our little example works like this – first we define the OutgoingReceiver to intercept all intents broadcasted with action READ_PHONE_STATE (i.e. phone calls, this is how we trigger the first receiver). Once the OutgoingReceiver intercepts the first broadcasted intent, it will broadcast the second custom intent using the context.sendBroadcast() method which will then be received by our second receiver IncomingReceiver.
As a proof of concept, here’s a screen shot of my log:
And so we see that once the call is initiated, it triggers the OutgoingReceiver and prints the first line, which then triggers the second broadcast intent, hits our IncomingReceiver, and prints the second line (in this order).
Of course, this is just the skeleton of how we can create custom intents and allow receivers to interact with one another but in your application you can create multiple receivers which get all intercept this intent, and in them you can extract different sets of data and perform different sets of operations, etc.
Hope this was helpful! Happy coding.
– jwei
Trackbacks
- Tweets that mention Custom Intents and Broadcasting with Receivers « Think Android -- Topsy.com
- Farhan's Blogs & Portal
- androidtutorialbyal.com » Blog Archive » Android Helpful links
- What is the name of the Activity that is called when the phone is ringing | PHP Developer Resource
- One update for widget « M. L. B.
Thanks a lot..!!It was very helpfull..!!n was pretty easy for a beginer like me to understand.!!thanx a lot..!!
Thanks for this example! Was a great help 🙂
Great example! One of the very few that I found that was clearly stated, but I have some seemingly basic questions:
Where do I put the two receiver classes? Are the receiver classes in separate files? Are they inner classes of my main Activity class? I’m very new to both Java and Android and think I’m missing some basic concepts here. Thanks in advance.
Hey Ethan,
I’d put them as separate classes and then declare them in your AndroidManifest file.
– jwei
Thanks so much. Your example worked perfectly and I set up an alarm successfully using your example as a guide. Your whole site is very well thought out.
Thanks again for your efforts,
Ethan
=D
Thanks Ethan
Can you publish a zip file of it all?
I can’t get my BroadcastReceiver to work, and a complete “gotta work” example like this would be fantastic.
jp
Hey Jim,
What exactly isn’t working? The example I provided should be “complete”.
– jwei
Jim,
I think what you are missing is simply an Activity.
You need to set up an activity that creates an intent and then sends an intent using sendBroadcast(intent). I used an alarmmanager, so mine is a bit different, but I guess you want something like this in your activity:
Intent intent = new Intent(mContext, OutgoingReceiver.class);
intent.putExtra(“someKey”, “someValue”);
sendBroadcast(intent);
JWei, correct me I’m wrong here. My alarm manager worked fine, but I’d love to know if I really understand.
Ethan
Thanks jwei512, Ethan. I have been desperately scouring for a solution…
Here’s the big picture.
I want to show the speed limit in a widget.
I want to update it when the speed limit changes (I have that code working).
AlarmManager won’t work since its not a timed event…
So the thought was, create two items, 1=widget, 2=status-bar-app
(that’s why I get lazy and beg people for complete project zip-files, since I am kind of new at Android and the simplest things trip me up…)
I never get this Intent.
The status bar app does this:
Uri uri = Uri.parse(“55”);
Intent intent = new Intent(“org.jamesp.gpscruise.UpdateWidgetAction”, uri);
sendBroadcast(intent);
The widget does this:
public class MyIntentReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
System.out.println(“GOT THE INTENT”);
}
}
forgot this part
hmm, is html grabbing my manifest?? I will post the intent here again…
ok, I took out the braces….
receiver android:name=”.MyIntentReceiver” android:label=”@string/widget_name”
intent-filter
action android:name=”org.jamesp.gpscruise.UpdateWidgetAction”
intent-filter
receiver
Jim,
I don’t know if “55” is a valid URI, but that probably shouldn’t matter, but I noticed you don’t have android:enabled=”true” in the manifest like JWei does.
Ethan
i need to make a forum haha
hopefully this problem was settled?
– jwei
Hi jwei,
How can we set data to custom actions? I used the below code snippet but it did not work. I am unable to receive data in other activity.
Intent i=new Intent();
i.setAction(“MY_ACTION”);
i.setData(Uri.parse(“android.resource://com.example.android.helloactivity” + R.string.button));
startActivity(i);
I defined the below activity in the manifest file.
Can I pass data to other activity? If so, can I pass it through setData() method with out using putExtras() ?
Hey Sarada,
So I think your problem lies here:
Uri.parse(“android.resource://com.example.android.helloactivity” + R.string.button)
You have to be careful that R.string.button is actually an integer that just contains the id of the string “button” defined in your strings.xml file.
Thus, when you do something like concatenating strings the way you just did it, you’re actually creating a string that looks like:
Uri.parse(“android.resource://com.example.android.helloactivity152308523″);
Which I think is not what you’re going for? If I’m wrong then maybe you want to use the i.setStringExtra() method instead of i.setData() method.
– jwei
Brilliant! That captured in one page more than the past 50 websites I’ve stared at trying to pass file path to a BroadcastReceiver that processes incoming text messages and needs to receive path changes from the main Activity. I wish I had found this 10 days ago.
I have a receiver that I can not figure out how to get the shared preferences from the main activity. I have an activity that allows the user to enter a phrase that when an sms comes in and matches that phrase will ring the phone. My broadcast receiver class extends broadcast receiver. I just cant figure out how to get the shared preferences set in the main activity. hope that makes sense.
Great example! Will this work if the broadcast receiver is in a different package than the class sending the custom intent?
Let me explain: I’m trying to set up a service that broadcasts custom intents for anyone who wants to make an app that will listen, but I’m having trouble getting it to work. Will this example work? (I’m not having any luck making it work.) If not, does anyone know where I can find any examples of this?
So just to be clear – you want to broadcast an intent that other applications installed on the phone can receive right?
Using this strategy of registering a custom intent and then broadcasting it, other applications should be able to receive it.
Just as how the Android OS broadcasts intents (i.e. intent android.intent.action.BATTERY_CHANGED) which any application can intercept, I don’t see how your application broadcasting an intent would be any different. Of course I may be wrong and the native intents from the system may have special properties that allow them to be intercepted across any application, this doesn’t seem like the case.
I want to be able to make my activity do something each time it receives an SMS, however, I have set the receiver, but I cant get it to work.
>
So basically, I am wrinting (or trying to) an app that receives an SMS and then uses a different class to send data over my wifi connection. I’ve been trying to figure out how to make the SmsReceiver class start the MessageSender class. From reading above, this is the best description of what “fits the bill” of what I am trying to do.
It looks like I need to register the sms_received intent and my_own_custom intent in the manifest, extend both activities to the broadcast receiver, and use
public static final String CUSTOM_INTENT = “my_own_custom”;
in the SmsReceiver class. Then I would make the MessageSender class something like this:
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(SmsReceiver.CUSTOM_INTENT))
Is that right or should I look elsewhere?
Hey Patrick,
So I think the flow of what you’re trying to do would look something like this…
1) Have a Receiver class that listens for the SMS_received intent.
2) Upon intercepting that intent, you could simply start a Service/Activity that is the MessageSender class, or if you want to use a broadcast you could broadcast your own custom intent (i.e. “message_sender_custom_intent” or something) and broadcast that.
3) If you choose to do the latter, then you would need a 3rd broadcast receiver that has an intent filter set to catch the custom intent. Once you receive the custom intent you can then start sending data over your wifi connection as desired.
Hope this helped.
– jwei
thank alot for this but i have a problem, can this be use for sending intents from Broadcast Receiver to Activity?? i appreciate ur help
You can start Activities from Receivers and when starting those Activities you can send data through the intent.
Otherwise, try looking into the Service class and seeing if there’s a way to receive an intent and update something without having to start a new Activity.
– jwei
Hi jwei,
howto send data from a service to another activity?
thanks..
Hey Mauladi,
Same way you would send it from Activity to Activity, just through an Intent and passing that intent to the startActivity() method.
– jwei
Hello,this tutorial was good.I am doing an android app for my mini-project.I want to give some statistics about call.This activity should come up when a phone call is made or phone call is ended.Is this possible..?If so,can u briefly explain??I would be thankful to you if you help me out.
chek out this with example of Broadcast reciver
http://androidtutorials60.blogspot.com/2011/04/broadcast-receivers-android-developer.html
Hi,
You have done a greate job , it is very understandable for beginners like me , thanks a lot for the greate post.
Also i would like to know broadCasting of intents…
i have a scenario like , in an app , having 3 tabs and in first tab i would navigate 3 activities , same for other tabs also,
initially fisrt tab tied with one activity then i need to push a new activity into the same tab .
if it is possible by sending broadcastintent then please explain me with some suitable example..
thanks for your greate work in helping me out
regards,
sathish
thanx:)
Nice post
Hi everyone,
I’ve got difficult for me question.
When I open mail client and I see phone number then I press it. After that I want to catch in BroadcastReceiver action that is being called by Android. Shortly – I want to swap it with my own Activity.
Any ideas ?
Marek, open the Android Market and install an app called Intent Intercept by AshtonBRSC. It will display intent information for you so that you can identify the intent action you need to use.
https://market.android.com/details?id=uk.co.ashtonbrsc.android.intentintercept
Very nice example
great! thanks a lot!
genial, muchisimas gracias!
it’s great
Thanks 🙂
clearly stated..
I did not find some thing this much straight forward.
Tanks a lot… actually …some how “Notification.FLAG_INSISTENT” is not working for some small notification sound like “beep” …so i am planning to use your idea and do a work around for my problem… thanks a lot
Nice post, Thank’s
thanx
Excellent web site. Plenty of useful information here. I am sending it to several pals ans additionally sharing in delicious. And obviously, thank you to your effort!
Thanks for this nice example.
Simply straightforward way to explain BroadcastReceivers. Thanks
Thanks! You helped me catch a bug in my code.
tahnks man…..
How does your example change if I want to create a custom receiver that has nothing to do with the phone? I want to set up a broadcast intent that keeps track of a wifi connection, and the device I’ll be running on has no phone.
Hey Rich,
It seems like you would need the WifiManager class. Here’s a good example of how you would do this:
http://stackoverflow.com/questions/2676044/broadcast-intent-when-network-state-has-changend
So basically, you would set up a broadcast receiver that listens for those intents above. I’m not sure what you mean by the device it’s running on “has no phone”, but as long as you’re on the Android OS this should work independent of device.
Let me know if that helps.
– jwei
We’re supplying a complete system to our customers. The software will be running on a Samsung Galaxy Tab 2, which has no cellular hardware. I need to make something that will alert the user if he loses Wifi connectivity. Thanks for the help.
Wow!! I spent 2 hrs on understanding how does this “receiver” works..and your post show me how simple it is!! Thanks
helped me to understand how i can create my own intent-action.
however Android doc says ” Those you invent should include the application package as a prefix” , so i think in your case it should be “jason.wei.apps.androidtest.TEST”
if I want the second broadcast Intent to be received by my activity then what should I do to register it with the activity..??
I want as soon as this intent is received by my activity, its onResume() method get called.
Nice one……….
Also found good tutorial on
Introduction_To_Broadcast_Receiver
Really helpful post!! Thanks. Even this website http://www.compiletimeerror.com/2013/03/android-broadcast-receiver-in-detail.html also addresses something similar.. Have a look.. Might help..
This sample is good for custom broadcast intent within application. But if we want to use this custom intent on the another app what would be the methodology… ie. to make our custom intent action as android global intent action