How to set speaker phone off when the app is killed by the "Recent App drawer"

161 views Asked by At

I implemented an app which has a button speaker, which is manually set "on" by myAudioManager.setSpeakerphoneOn(true) and "off" vice-versa. But the bug is when you close the application while the speaker is on, it forgets the speaker was on. The next time, the speaker remains on and the call is by default in speaker mode. I don't want to set speaker off when app is in background, only when the app gets killed it has to be set off. onDestroy() works good, but it wont gets called all the time according to the lifecycle.

2

There are 2 answers

7
Strider On BEST ANSWER

Use a service like:

public class FirstService extends Service {

    private AudioManager audioManager;

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        audioManager.setSpeakerphoneOn(false);  //Turn of speaker
    }
}

public void onDestroy () Added in API level 1

Called by the system to notify a Service that it is no longer used and is being removed. The service should clean up any resources it holds (threads, registered receivers, etc) at this point. Upon return, there will be no more calls in to this Service object and it is effectively dead. Do not call this method directly. More info here

Add service to Manifest:

<service android:name=".FirstService" ></service>

And start the service in your activity's onCreate() method with:

startService(new Intent(this, FirstService.class));

Hope this helps you out.

8
Samir Bhatt On

You need to manage audio manager for android lifecycle's evry method.