IntentFilter filterss = new IntentFilter();
filterss.addAction("android.intent.action.PHONE_STATE");
phoneReceiver = new PhoneReceiver(new PhoneReceiver.PhoneListener() {
@Override
public void status(int type) {//0未知 1挂断 2接通、拨打 3响铃
//TODO 此处处理自己的业务即可
}
});
registerReceiver(phoneReceiver, filterss);
在onDestory中取消注册:
if (phoneReceiver != null) {
unregisterReceiver(phoneReceiver);
phoneReceiver = null;
}
下面是PhoneReceiver的全部代码:
package tv.buka.roomSdk.receiver;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
/**
* 去电、来电监听的广播
*
* Created by hwk on 2018/7/12.
*/
public class PhoneReceiver extends BroadcastReceiver {
private boolean isListen = false;
private PhoneListener phoneListener;
public PhoneReceiver(PhoneListener phoneListener) {
this.phoneListener = phoneListener;
}
@Override
public void onReceive(Context context, Intent intent) {
if (!isListen) {
TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
if (tm != null) {
tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
isListen = true;
}
}
//去电
if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
//这个地方只有你拨号的瞬间会调用
Log.e("PhoneReceiver", "call OUT:" + phoneNumber);
}
}
private PhoneStateListener listener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, final String incomingNumber) {
//state 当前状态 incomingNumber,貌似没有去电的API
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
if (TextUtils.isEmpty(incomingNumber)) {
phoneListener.status(0);
} else {
phoneListener.status(1);
}
//不管是去电还是来电通话结束都会调用,不管是不是你挂的
Log.e("PhoneReceiver", "挂断" + incomingNumber);
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
phoneListener.status(2);
//如果是来电,这个必须点击接听按钮才会调用
//如果是拨打,那么一开始就会调用,并不是打通了之后才会调用
Log.e("PhoneReceiver", "摘机状态,接听或者拨打" + incomingNumber);
break;
case TelephonyManager.CALL_STATE_RINGING:
phoneListener.status(3);
//只有来电的时候会调用
Log.e("PhoneReceiver", "响铃:来电号码:" + incomingNumber);
break;
}
}
};
public interface PhoneListener {
void status(int type);//0未知 1挂断 2接通、拨打 3响铃
}
}