借鉴链接安卓代替系统默认电话应用(Android 6.0+)与电话状态监听 - 简书
一、继承InCallService
public class PhoneCallService extends InCallService {
private final static String TAG = "PhoneCallService";
private BroadcastReceiver headsetReceiver = null;
private Call.Callback callback = new Call.Callback() {
@Override
public void onStateChanged(Call call, int state) {
super.onStateChanged(call, state);
Log.d(TAG, "onStateChanged, state == " + state);
switch (state) {
case Call.STATE_ACTIVE:// 通话中
break;
case Call.STATE_DISCONNECTED: // 通话结束
Intent intent = new Intent();
intent.setAction("com.action.CallEnd");
sendBroadcast(intent);
break;
}
}
};
@Override
public void onCallAdded(Call call) {
super.onCallAdded(call);
Log.d(TAG, "onCallAdded");
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (audioManager.isWiredHeadsetOn()) {
Log.d(TAG, "isWiredHeadsetOn");
this.setAudioRoute(CallAudioState.ROUTE_WIRED_HEADSET) ;
} else {
this.setAudioRoute(CallAudioState.ROUTE_SPEAKER);
}
call.registerCallback(callback);
PhoneCallManager.call = call; // 传入call
CallType callType = null;
if (call.getState() == Call.STATE_RINGING) {
callType = CallType.CALL_IN;
} else if (call.getState() == Call.STATE_CONNECTING) {
callType = CallType.CALL_OUT;
}
if (callType != null) {
Call.Details details = call.getDetails();
String phoneNumber = details.getHandle().toString().substring(4)
.replaceAll("%20", ""); // 去除拨出电话中的空格
Intent intent = new Intent(getBaseContext(), PhoneCallActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_MIME_TYPES, callType);
intent.putExtra(Intent.EXTRA_PHONE_NUMBER, phoneNumber);
Log.d(TAG, "onCallAdded, callType : " + callType + ", phoneNumber : " + phoneNumber);
startActivity(intent);
}
}
&