I am attempting to make an application that reads text messages. The application works fine, when I get a text message, the message is displayed in a toast along with the phone number. The problem is, even with the application closed, ie not in the foreground, it still shows the toast when I get a text message. I have used a task killer application, and it still shows the toast. The only way to not show the toast is to unistall the application. I am using this website as a tutorial
http://www.apriorit.com/our-company/dev-blog/227-handle-sms-on-android
I have done everything in the tutorial except for the encryption.
Any help is appreciated!
Thanks,
Chris
That’s the correct behavior actully. Every time you get a message, the system sends a SMS broadcast. Since your application declares in it’s manifest that it wants to receive such broadcasts, a new instance of your BroadcastReceiver will be created and executed every time.
If you want to execute the receiver only at certain times (in this case when your app is in the foreground), you have to register and unregister it dynamically in code instead of the manifest by using
Context.registerReceiver()andContext.unregisterReceiver().How to do this exactly?
Here’s a short example. I’ll assume that you have written your own class that extends BroadcastReceiver and handles stuff in
onReceive(). The name of this class in this example isSmsReceiver, like in the linked tutorial.Our goal is to receive broadcasts only when one activity is in the foreground, which means you should also have one class that extends Activity and displays UI like a normal app.
First of all we need an actual instance of the receiver as a class member. Add something like this to your activity class:
Sidenote: That’s actually one of the main differences between registering in the manifest and in code:
Alright, great. Now we just have to register and unregister this receiver when the activity comes into the foreground and goes out of it. Have a look at the diagram in the Activity class doc, the framework methods called in these events are
onResume()andonPause().Add the following lines to your
onResume()method:What we did here is actually pretty simple. It’s the code-equivalent of the manifests
<receiver />tag. We created an intent filter with a broadcast that we like to receive and register our receiver with it.The next step is to unregister in
onPause(). Again, either add this line or createonPause()if you have not yet.Pretty straightforward – take our receiver instance and unregister it when the app is about to go into the background. And that’s all the magic, everything should work as intended. Don’t forget to delete the whole
<receiver />tag in your manifest though, when you work with your existing code. Otherwise you would register your receiver in two ways.