我正在使用broadcastreceiver来检测拨出呼叫并在它开始拨号后启动服务。服务已启动。现在我想在通话结束或拨号结束后停止服务。
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_NEW_OUTGOING_CALL.equals(intent.getAction())) {
intent = new Intent(context, serv.class);
context.startService(intent);
}
if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(
TelephonyManager.EXTRA_STATE_IDLE)) {
intent = new Intent(context, serv.class);
context.stopService(intent);
}
}
答案 0 :(得分:1)
try {
//to Fix Lolipop broadcast issue.
long subId = intent.getLongExtra("subscription", Long.MIN_VALUE);
if (subId < Integer.MAX_VALUE) {
if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
savedNumber = intent.getExtras().getString("android.intent.extra.PHONE_NUMBER");
} else {
String stateStr = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
String number = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
int state = 0;
if (stateStr.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
state = TelephonyManager.CALL_STATE_IDLE;
} else if (stateStr.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
state = TelephonyManager.CALL_STATE_OFFHOOK;
} else if (stateStr.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
state = TelephonyManager.CALL_STATE_RINGING;
}
onCallStateChanged(context, state, number);
}
}
} catch (Exception e) {
e.printStackTrace();
}
public void onCallStateChanged(final Context context, int state, String number) {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
isIncoming = true;
callStartTime = new Date();
savedNumber = number;
TimerTask tt = new TimerTask() {
@Override
public void run() {
onIncomingCallStarted(context, savedNumber, callStartTime);
}
};
Timer t = new Timer();
t.schedule(tt, 1000);
// TimerTask tt = new TimerTask() {
// @Override
// public void run() {
// }
// };
// onIncomingCallStarted(context, savedNumber, callStartTime);
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
if (lastState == TelephonyManager.CALL_STATE_RINGING) {
isIncoming = true;
callStartTime = new Date();
onReceiveCall(context, savedNumber, callStartTime, "received");
} else {
isIncoming = false;
}
break;
case TelephonyManager.CALL_STATE_IDLE:
if (lastState == TelephonyManager.CALL_STATE_RINGING) {
onMissedCall(context, savedNumber, callStartTime, "Missed");
} else if (isIncoming) {
onIncomingCallEnded(context, savedNumber, callStartTime, new Date());
} else {
onOutgoingCallEnded(context, savedNumber, callStartTime, new Date(), "outgoing");
}
break;
}
lastState = state;
}