Search code examples
androidandroid-activitybroadcastreceiverandroid-service

Listening/Acting on Call State changes - service? activity? receiver?


I'm fairly new to Android development and am working on an app which allows the user to activate and deactivate a feature which responds to incoming calls. i.e. if they turn the feature on, something happens when they receive a call, if the feature is turned off, nothing out of the ordinary happens.

I've got the basics of TelephonyManager and PhoneStateListener sorted out - I can create a listener for the call state when the feature is enabled and remove it when the feature is disabled. Enabling and disabling the feature is done via the UI which is a simple Activity.

When a call is received, the feature involves using data stored in the app's preferences. If the feature is enabled it should run until it is switched off, regardless of if the app is active... Ideally, if the feature is enabled (status of feature stored in app preferences), it should start up after a reboot.

My question is, what is the best way to implement this?

I originally started working on a service (which is started/stopped by enabling/disabling the feature)...

I then noticed that the call state listener worked just fine when set/unset directly via the activity, but suspect this may run into problems when the activity ends/is garbage collected...? (I don't know much about how Android handles such things)

I also saw mention of receivers / broadcast receivers which seem like something else I could use. At first glance, they appear to be an "always on" thing, but I guess I could check the app preferences to see if the feature is enabled whenever a call is received...

I haven't really looked into making sure the feature works after booting the phone if it is enabled. I also haven't really looked into accessing the app preferences from a service/receiver - should be possible, though...

Any thoughts or suggestions would be great. Code samples or links to tutorials would be brilliant as well.


Solution

  • I talked to someone and did a bit more research, and a broadcast receiver was indeed what I need. It's remarkably simple, actually.

    Mostly followed the tutorial at http://www.vogella.de/articles/AndroidServices/article.html#receiver

    Used How to edit shared preferences in an activity other than the one it is created in? when figuring out how to access preferences.