Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping & starting music on incoming calls

I have implemented an activity that plays media from a URL in Android.

In order to add pause functionality when a call is incoming I created a receiver that sets a variable when the call is coming. The activity reads this variable in onPause(), pauses the music and resets it. When the call is done and the activity is resumed, the music is resumed in onResume().

This works fine as long the activity has the focus. If I go back to home screen while the music is playing, and then the call comes, onPause() is not called. Hence, I can't stop and start the music.

Has anybody implemented a media player that intercepts incoming/outgoing calls and stops/starts music correctly?

like image 650
user669231 Avatar asked Apr 10 '11 07:04

user669231


People also ask

What do you mean by stopping?

1a : to cease activity or operation his heart stopped the motor stopped. b : to come to an end especially suddenly : close, finish The talking stopped when she entered the room. 2a : to cease to move on : halt.

What is the synonym of stopping?

desist (from), lay off (of), refrain (from)


1 Answers

There are a few things you can do:

First of all, you can listen for changes in the call state using a PhoneStateListener. You can register the listener in the TelephonyManager:

PhoneStateListener phoneStateListener = new PhoneStateListener() {     @Override     public void onCallStateChanged(int state, String incomingNumber) {         if (state == TelephonyManager.CALL_STATE_RINGING) {             //Incoming call: Pause music         } else if(state == TelephonyManager.CALL_STATE_IDLE) {             //Not in call: Play music         } else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {             //A call is dialing, active or on hold         }         super.onCallStateChanged(state, incomingNumber);     } }; TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); if(mgr != null) {     mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); } 

Remember to unregister the listener when it's no longer needed using the PhoneStateListener.LISTEN_NONE:

TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); if(mgr != null) {     mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE); } 

For more information read the documentation.

Another thing you can do is listening for the broadcast android.intent.action.PHONE_STATE. It will contain the extra TelephonyManager.EXTRA_STATE which will give you information about the call. Take a look at the documentation here.

Please note that you'll need the android.permission.READ_PHONE_STATE-permission in both cases.

like image 69
Kaloer Avatar answered Sep 30 '22 14:09

Kaloer