Search code examples
androidbroadcastreceiversendmessagesmsmanager

sending message in android two times instead of once


I want to send SMS after call ends, my app sends the SMS but the problem is that it is sending it twice in every call and I don't know where the problem is (I want to send one sms every time not twice)

Here is my code:

public class Receiver extends BroadcastReceiver {  
  SmsManager smsmanager=SmsManager.getDefault(); 
  public void onReceive(Context context, Intent intent) {

  if (phoneNumber != null){

     telephonyService.endCall();
     smsmanager.sendTextMessage(phoneNumber, null, "message", null, null);

  }
}

on Manifest:

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

Solution

  • Your Receiver will be called every time the phone state changes (ringing, in call, ...).
    You must filter the corresponding action:

      // Keep track of the previous state
      String previousState;
    
      public void onReceive(Context context, Intent intent) {
        String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
        if (CALL_STATE_IDLE.equals(state) && CALL_STATE_OFFHOOK.equals(previousState) {
          // send sms here
        }
        previousState = state;
      }