I have read Detecting outgoing call and call hangup event in android
I want to do an app to detect call event in background as a service, I think I should choose BroadcastReceiver, because the app will keep detect call even if I exit the app. I think the only way to stop detecting call is uninstall the app when I use BroadcastReceiver.
If I choose PhoneStateListener, I think the app will stop detecting call if I exit the app.
Right?
Thanks!
In my opinion the best way to go is using the simplest solution. That said, PhoneStateListener will do exactly what you want - detect call event in background:
public class IncomingCallReciever extends BroadcastReceiver {
private Context mContext;
private Intent mIntent;
@Override
public void onReceive(Context context, Intent intent) {
mContext = context;
mIntent = intent;
TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
int events = PhoneStateListener.LISTEN_CALL_STATE;
tm.listen(phoneStateListener, events);
}
private final PhoneStateListener phoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
String callState = "UNKNOWN";
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
callState = "IDLE";
break;
case TelephonyManager.CALL_STATE_RINGING:
// -- check international call or not.
if (incomingNumber.startsWith("00")) {
Toast.makeText(mContext,"International Call- " + incomingNumber,Toast.LENGTH_LONG).show();
callState = "International - Ringing (" + incomingNumber+ ")";
} else {
Toast.makeText(mContext, "Local Call - " + incomingNumber, Toast.LENGTH_LONG).show();
callState = "Local - Ringing (" + incomingNumber + ")";
}
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
String dialingNumber = mIntent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
if (dialingNumber.startsWith("00")) {
Toast.makeText(mContext,"International - " + dialingNumber,Toast.LENGTH_LONG).show();
callState = "International - Dialing (" + dialingNumber+ ")";
} else {
Toast.makeText(mContext, "Local Call - " + dialingNumber,Toast.LENGTH_LONG).show();
callState = "Local - Dialing (" + dialingNumber + ")";
}
break;
}
Log.i(">>>Broadcast", "onCallStateChanged " + callState);
super.onCallStateChanged(state, incomingNumber);
}
};
}
To access the states, you need to declare the permissions in manifest file:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
It is pretty amazing what PhoneStateListener.LISTEN_CALL_STATE do, practically making it much easier than thought at first sight, because it provide you all you need to monitor call events.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With