标签:
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!
标签:
原文地址:http://www.cnblogs.com/jiangui/p/4303376.html