Reputation: 151
In one of my app I have to detect external sound even app is in background. I have a question on it.
Is it possible to detect external sound continuously even app is in background mode or closed ? If so then will it affect on device battery ?
If it is not possible then is there any alternate way to achieve this ?
Plz let me know about this .
Thanks,
Upvotes: 0
Views: 846
Reputation: 983
I'm currently working on something like this, and I have used a class that extends service http://developer.android.com/guide/components/services.html.
As people mentioned above if it is running continuously you may get the android ANR kill wait option. There are two ways I worked around this.
make sure that your service is not running on the main ui thread, either using Async or just threading it yourself. Beyond that try to get it to do as little work as you can to avoid that ANR.
I limited the amount of time each service lasts. ie, the service listens for a few seconds, runs analysis, saves it, and if conditions are met , creates a new service before calling stopSelf(). This can be a bit hacky, but it can also work depending on what you actually doing with the audio.
Upvotes: 2
Reputation: 1017
EDIT: I might have misunderstood you
Here's a snippet I use to see if audiofocus changes in conjunction with my MediaPlayer in a Service. You won't know what is playing but you will know if something external is requesting audio:
OnAudioFocusChangeListener afChangeListener = new OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
//Manage audiofocus changes
if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT
&& mp != null) {
if (mp.isPlaying())
pausePlaying();
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN
&& mp != null) {
if (!mp.isPlaying())
pausePlaying();
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS
&& mp != null) {
am.abandonAudioFocus(afChangeListener);
if (mp.isPlaying())
pausePlaying();
Log.d("FOCUS", "Focus Changed AUDIOLOSS ");
}
}
};
Upvotes: 0