码迷,mamicode.com
首页 > 其他好文 > 详细

andriod电话状态监听-来电去电

时间:2015-02-27 16:53:00      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

Android在电话状态改变是会发送action为android.intent.action.PHONE_STATE的广播,

而拨打电话时会发送action为 android.intent.action.NEW_OUTGOING_CALL的广播

android 在音乐播放器里面对电话状态的监听,比如:正在播放音乐,来电(去电)则暂停音乐,挂断电话则继续播放音乐。

一、电话活动监听广播

public class PhoneReceiver extends BroadcastReceiver {

  private Context mContext;
  private String mAction;
  private Intent mIntent;

  public PhoneReceiver(){}
  public PhoneReceiver(Context context){
    super();
    mContext = context;
  }

  @Override
  public void onReceive(Context context, Intent intent) {
    mAction = intent.getAction();
    if(mAction.equals(Intent.ACTION_NEW_OUTGOING_CALL)){
    //去电
      mIntent = new Intent();
      mIntent.setAction(BroadcastFlag.MUSIC_STOP);
      mContext.sendBroadcast(mIntent);
    }else{
      //来电
      TelephonyManager manager = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
      manager.listen(stateListener, PhoneStateListener.LISTEN_CALL_STATE);
    }
  }

  PhoneStateListener stateListener = new PhoneStateListener(){

    public void onCallStateChanged(int state, String incomingNumber) {
      super.onCallStateChanged(state, incomingNumber);
      switch(state){
        case TelephonyManager.CALL_STATE_IDLE:
          //挂断
          mIntent = new Intent();
          mIntent.setAction(BroadcastFlag.MUSIC_START);
          mContext.sendBroadcast(mIntent);
        break;
        case TelephonyManager.CALL_STATE_OFFHOOK:
          //接听
        case TelephonyManager.CALL_STATE_RINGING:
          //响铃
          mIntent = new Intent();
          mIntent.setAction(BroadcastFlag.MUSIC_STOP);
          mContext.sendBroadcast(mIntent);
        break;
      }
    };
  };
}

二、在音乐播放服务(MusicPlayService)中注册广播

 

技术分享

三、在AndroidManifest.xml文件添加权限

<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"></uses-permission>

 

OK!

 

andriod电话状态监听-来电去电

标签:

原文地址:http://www.cnblogs.com/jiangui/p/4303376.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!