The following code is the state of listening to the phone, the code simply do not introduce direct look at the code:
Copy Code code as follows:
Private Boolean mresumeaftercall = false;
Private Phonestatelistener Mphonestatelistener = new Phonestatelistener () {
@Override
public void oncallstatechanged (int state, String incomingnumber) {
if (state = = telephonymanager.call_state_ringing) {
Audiomanager Audiomanager = (audiomanager) getsystemservice (Context.audio_service);
int ringvolume = Audiomanager
. Getstreamvolume (audiomanager.stream_ring);
if (Ringvolume > 0) {
Mresumeaftercall = (player.isplaying () | | mresumeaftercall);
try {
Stub.pause ();
catch (RemoteException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
else if (state = = Telephonymanager.call_state_offhook) {
Pause the music while a conversation was in progress
Mresumeaftercall = (player.isplaying () | | mresumeaftercall);
try {
Stub.pause ();
catch (RemoteException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
else if (state = = Telephonymanager.call_state_idle) {
Start playing again
if (Mresumeaftercall) {
Resume playback only if music is playing
When the call was answered
try {
Stub.resume ();
catch (RemoteException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
Mresumeaftercall = false;
}
}
}
};
When it is used, it is added in the oncreate of the service, as follows:
Copy Code code as follows:
public void OnCreate () {
Player = new MediaPlayer ();
Super.oncreate ();
Telephonymanager tmgr = (telephonymanager) getsystemservice (Context.telephony_service);
Tmgr.listen (Mphonestatelistener, phonestatelistener.listen_call_state);
Intentfilter filter = new Intentfilter ();
Filter.addaction (Servicecmd);
Filter.addaction (pause_action);
Receiver = new Musicservicereceiver ();
Registerreceiver (receiver, filter);
}
You can delete it in the OnDestroy.
Copy Code code as follows:
public void OnDestroy () {
LOG.E (TAG, "OnDestroy" +player.isplaying ());
System.out.println ("OnDestroy");
Unregisterreceiver (receiver);
Player.release ();
Player = null;
Telephonymanager tmgr = (telephonymanager) getsystemservice (Context.telephony_service);
Tmgr.listen (Mphonestatelistener, 0);
Super.ondestroy ();
}