Saty
Saty

Reputation: 2621

Broadcast receiver calls twice EXTRA_STATE_RINGING state causing invariant data

I am trying to save call details when call comes so I implemented a broadacast receiver which listens to PHONE STATE. The problem comes when the call comes, it goes to EXTRA_STATE_RINGING twice where I implemented the logic so my logic called up twice causing invariant data.

private static final String ACTION_IN = "android.intent.action.PHONE_STATE";

Below is the code for BroadCastReceiver's onReceieve()

public void onReceive(Context context, Intent intent) {
    ctx = context;
    if (intent.getAction().equals(ACTION_IN)) {
        Log.v("onReceive", "ACTION IN");
        if ((bundle = intent.getExtras()) != null) {
            Log.v("onReceive", "Bundle != NULL");
            state = bundle.getString(TelephonyManager.EXTRA_STATE);
            Log.v("onReceive", "state: "+state);
            if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
            //businesslogic
            }
            }

            }
            }

I have following permission in the manifest

 <uses-permission android:name="android.permission.READ_PHONE_STATE"/>  

my receiver is defined as this in manifest

<receiver android:name="IncomingCallInterceptor" >                    
<intent-filter android:priority="999">                                                 
             <action android:name="android.intent.action.PHONE_STATE"/> 
        </intent-filter>       
    </receiver>

Upvotes: 4

Views: 1674

Answers (1)

Psypher
Psypher

Reputation: 10839

Try this out, it does not implement the business logic at EXTRA_STATE_RINGING, it sets if only after user disconnects the call(CALL_STATE_IDLE ).

public void onReceive(Context context, Intent intent) {
    ctx = context;
    if (intent.getAction().equals(ACTION_IN)) {
        Log.v("onReceive", "ACTION IN");
        if ((bundle = intent.getExtras()) != null) {
            Log.v("onReceive", "Bundle != NULL");
            state = bundle.getString(TelephonyManager.EXTRA_STATE);
            Boolean singlecallstate=false;
    switch (state) {
        case TelephonyManager.EXTRA_STATE_RINGING:
           singlecallstate=true;
           //any other code you want
        case TelephonyManager.CALL_STATE_IDLE:
       if(singlecallstate){
           //business logic
          singlecallstate=false;
          }
    }
  }
}

Upvotes: 1

Related Questions