欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

android音乐播放器监听电话状态实现代码

程序员文章站 2022-10-09 13:56:17
如下代码是监听电话的状态,代码简单不做介绍直接看代码:复制代码 代码如下: private boolean mresumeaftercall = false;&n...

如下代码是监听电话的状态,代码简单不做介绍直接看代码:

复制代码 代码如下:

 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 is 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 was playing
     // when the call was answered
     try {
      stub.resume();
     } catch (remoteexception e) {
      // todo auto-generated catch block
      e.printstacktrace();
     }
     mresumeaftercall = false;
    }
   }
  }
 };

使用的时候呢,就在service 的oncreate 里面添加,如下:
复制代码 代码如下:

 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);
 }

在ondestroy 里面删除就可以了
复制代码 代码如下:

 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();
 }