andriod电话状态监听-来电去电 - 没哈啊

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)中注册广播

 

andriod电话状态监听-来电去电 - 没哈啊_第1张图片

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


 

OK!

 


本文链接: andriod电话状态监听-来电去电,转载请注明。

你可能感兴趣的:(andriod,电话,状态)