I am attempting to have my application recognize when there is a missed call. I have created a BroadcastReceiver that detects when the phone's state has changed. Here is my onReceive()
method:
public void onReceive(Context context, Intent intent) {
boolean ringing = false, callReceived = false;
String callerPhoneNumber = "";
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (TelephonyManager.EXTRA_STATE_RINGING.equals(state)) {
ringing = true;
Bundle bundle = intent.getExtras();
callerPhoneNumber= bundle.getString("incoming_number");
if (ringing) {
Toast.makeText(context, "Phone call from: " + callerPhoneNumber, Toast.LENGTH_LONG).show();
}
}
if (TelephonyManager.EXTRA_STATE_OFFHOOK.equals(state)) {
callReceived = true;
Toast.makeText(context, "Call received.", Toast.LENGTH_LONG).show();
}
if (TelephonyManager.EXTRA_STATE_IDLE.equals(state)) {
// Toast.makeText(context, "Phone is idle", Toast.LENGTH_LONG).show();
if (ringing) {
Toast.makeText(context, "ringing is true", Toast.LENGTH_LONG).show();
}
// if (ringing && !callReceived) {
// Toast.makeText(context, "It was A MISSED CALL from : " + callerPhoneNumber, Toast.LENGTH_LONG).show();
// }
}
The issue I am having is the application detects when the phone is ringing, sets ringing
to true
, and shows the appropriate toast message. However, when the phone's state is idle
, it does not enter the if (ringing)
statement to show the ringing is true
toast message. However, if I comment in the toast message just above it, it will correctly print that the Phone is idle
.
Is it possible that ringing
is being reset to false
somewhere between the phone ringing and the phone becoming idle again?
You can not store any "state" information in a broadcast receiver. If you want to do a comparison old state / new state, I think you can use a service.