When playing music on a mobile phone, we want to listen to the phone status. Of course, there is no phone function on the mid, and no listening is required.
As follows:CodeIt is the status of the phone number to listen to. You can directly view the code without introducing the Code:
Private Boolean listener = false; <br/> private phonestatelistener mphonestatelistener = new phonestatelistener () {<br/> @ override <br/> Public void oncallstatechanged (INT state, string incomingnumber) {<br/> If (State = telephonymanager. call_state_ringing) {<br/> audiomanager = (audiomanager) getsystemservice (context. audio_service); <br/> int ringvolume = audiomanager <br/>. getstreamvolume (audiomanager. stream_ring); <br/> If (ringvolume> 0) {<br/> mresumeaftercall = (player. isplaying () | mresumeaftercall); <br/> try {<br/> stub. pause (); <br/>}catch (RemoteException e) {<br/> // todo auto-generated Catch Block <br/> E. printstacktrace (); <br/>}< br/>} else if (State = telephonymanager. call_state_offhook) {<br/> // pause the music while a conversation is in progress <br/> mresumeaftercall = (player. isplaying () | mresumeaftercall); <br/> try {<br/> stub. pause (); <br/>}catch (RemoteException e) {<br/> // todo auto-generated Catch Block <br/> E. printstacktrace (); <br/>}< br/>} else if (State = telephonymanager. call_state_idle) {<br/> // start playing again <br/> If (mresumeaftercall) {<br/> // Resume playback only if music was playing <br/> // when the call was answered <br/> try {<br/> stub. resume (); <br/>}catch (RemoteException e) {<br/> // todo auto-generated Catch Block <br/> E. printstacktrace (); <br/>}< br/> mresumeaftercall = false; <br/>}< br/> };
When using it, add it in oncreate of Service as follows:
Public void oncreate () {<br/> player = new mediaplayer (); <br/> super. oncreate (); <br/> telephonymanager tmgr = (telephonymanager) getsystemservice (context. telephony_service); <br/> tmgr. listen (mphonestatelistener, phonestatelistener. listen_call_state); <br/> intentfilter filter = new intentfilter (); </P> <p> filter. addaction (servicecmd); <br/> filter. addaction (pause_action); <br/> receiver = new musicservicereceiver (); <br/> registerreceiver (receiver, filter); <br/>}
Delete it in ondestroy.
Public void ondestroy () {<br/> // log. E (TAG, "ondestroy" + player. isplaying (); <br/> // system. out. println ("ondestroy"); <br/> unregisterreceiver (receiver); <br/> player. release (); <br/> player = NULL; </P> <p> telephonymanager tmgr = (telephonymanager) getsystemservice (context. telephony_service); <br/> tmgr. listen (mphonestatelistener, 0); <br/> super. ondestroy (); <br/>}< br/>