Android SMS Delivery Intent always return -1

2019-06-16 03:32发布

问题:

I'm facing a weird problem on Android. I want to listen for a delivery intent when I send a text message through my app. Here is what I've done so far:

private void shootSMS(String number,long currentTime){
    SmsManager smsManager = SmsManager.getDefault();

    Intent sentIntent = new Intent(SentBroadcastReceiver.SENT_ACTION);
    Intent deliveredIntent = new Intent(DeliveredBroadcastReceiver.DELIVERED_ACTION);

    Bundle b = new Bundle();
    b.putString("num",number);
    b.putString("record_time",currentTime+"");

    sentIntent.putExtras(b);
    deliveredIntent.putExtras(b);


    PendingIntent sentPendingIntent = PendingIntent.getBroadcast(this,(int)currentTime,sentIntent,PendingIntent.FLAG_ONE_SHOT);
    PendingIntent deliveredPendingIntent = PendingIntent.getBroadcast(this,(int)currentTime,deliveredIntent,PendingIntent.FLAG_ONE_SHOT);
    smsManager.sendTextMessage(number,null,getString(R.string.app_name),sentPendingIntent,deliveredPendingIntent);

}

Now the problem is that when the onReceive() methods of my broadcast receivers are called I call the getResultCode() method, and it always return -1! Even if the phone is turned off, so it makes it impossible to track whether the SMS is delivered or not!

I checked the number with the GoSMSPro and sent a SMS which failed. The interesting thing is that when I put my phone in Airplane Mode I get a Result Code equal to 2 which is SmsManager.RESULT_ERROR_RADIO_OFF

Now the question is what's wrong in here?

回答1:

The documentation on sendTextMessage states:

sentIntent: if not NULL this PendingIntent is broadcast when the message is successfully sent, or failed. The result code will be Activity.RESULT_OK...

If you go look at Activity.RESULT_OK the value is -1.

So the resultCode of -1 is actually RESULT_OK.

In general it is best not to look at numeric values but to try to figure out which constant they are representing.



回答2:

do like this:

private void sendSms(String phonenumber, String message) {
    SmsManager manager = SmsManager.getDefault();

    PendingIntent piSend = PendingIntent.getBroadcast(this, 0, new Intent(
            SMS_SENT), 0);
    PendingIntent piDelivered = PendingIntent.getBroadcast(this, 0,
            new Intent(SMS_DELIVERED), 0);

        int length = message.length();

        if (length > MAX_SMS_MESSAGE_LENGTH) {
            ArrayList<String> messagelist = manager.divideMessage(message);

            ArrayList<PendingIntent> sentIntents = new ArrayList<PendingIntent>();
            ArrayList<PendingIntent> deliveryIntents = new ArrayList<PendingIntent>();

            int numParts = messagelist.size();
            ;
            for (int i = 0; i < numParts; i++) {
                sentIntents.add(PendingIntent.getBroadcast(this, 0,
                        new Intent(
                                SMS_SENT), 0));
                deliveryIntents.add(PendingIntent.getBroadcast(this, 0,
                        new Intent(SMS_DELIVERED), 0));
            }

            manager.sendMultipartTextMessage(phonenumber, null,
                    messagelist, sentIntents, deliveryIntents);
        } else {
            manager.sendTextMessage(phonenumber, null, message, piSend,
                    piDelivered);
        }
}  

and your Receiver:
note that use "Activity.RESULT_OK" instead number

private BroadcastReceiver deliveredreceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String info = "Delivery information: ";

        switch (getResultCode()) {
        case Activity.RESULT_OK:
            info += "delivered";
            break;
        case Activity.RESULT_CANCELED:
            info += "not delivered";
            break;
        }

        Toast.makeText(getBaseContext(), info, Toast.LENGTH_SHORT).show();
    }
};  

permission:

 <uses-permission android:name="android.permission.READ_SMS"></uses-permission>
 <uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
 <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>  

this permission use for sending and receiving sms.



回答3:

Try This approach : To send a text message use sendTextMessage from SMS Manager.

 sendTextMessage(String destinationAddress, String  scAddress, String text,PendingIntent sentIntent, PendingIntent deliveryIntent)

The first Pending Intent parameter (sentIntent) is fired when the message is either successfully sent or failed. The result code for the Broadcast receiever that receives this Intent will be one of the following.

Activity.RESULT_OK - To indicate a successful transmission.
Sms.Manager.RESULT_ERROR_GENERIC_FAILURE - To indicate a nonspecific failure
Sms.Manager.RESULT_ERROR_RADIO_OFF - To indicate the phone radio is turned off
Sms.Manager.RESULT_ERROR_NULL_PDU - To indicate a PDU failure.
SmsManager.RESULT_ERROR_NO_SERVICE - To indicate that no cellular service is currently available.

The second Pending parameter(deliveryIntent) is fired only after the recipient receives your SMS message.

After sent and delivery events display appropriate messages through Toast.

activity_main.xml

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@drawable/bg"
     >

 <TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/pn"
    android:textSize="15sp"    
    android:textColor="@android:color/white"
    android:background="@android:color/black"
    />

 <EditText
     android:id="@+id/phno"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:background="@android:color/darker_gray"
     android:ems="10" >        
 </EditText>
 <TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/msg"
    android:textSize="15sp"    
    android:textColor="@android:color/white"
    android:background="@android:color/black"
    />
  <EditText
        android:id="@+id/smstxt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
          android:background="@android:color/darker_gray"
        android:lines="5"
        android:gravity="top" />  
 <Button
        android:id="@+id/send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/b1" /> 


   </LinearLayout>

MainActivity.java

import android.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
 Button btnSend;
 EditText etPhoneNo;
 EditText etMsg;

  @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  etPhoneNo = (EditText) findViewById(R.id.phno);
  etMsg = (EditText) findViewById(R.id.smstxt);
  btnSend = (Button) findViewById(R.id.send);

   btnSend.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    String phoneNo = etPhoneNo.getText().toString();
    String msg = etMsg.getText().toString();
    try {

      String SENT = "sent";
     String DELIVERED = "delivered";

      Intent sentIntent = new Intent(SENT);
     /*Create Pending Intents*/
     PendingIntent sentPI = PendingIntent.getBroadcast(
       getApplicationContext(), 0, sentIntent,
       PendingIntent.FLAG_UPDATE_CURRENT);

      Intent deliveryIntent = new Intent(DELIVERED);

      PendingIntent deliverPI = PendingIntent.getBroadcast(
       getApplicationContext(), 0, deliveryIntent,
       PendingIntent.FLAG_UPDATE_CURRENT);
     /* Register for SMS send action */
     registerReceiver(new BroadcastReceiver() {

       @Override
      public void onReceive(Context context, Intent intent) {
       String result = "";

        switch (getResultCode()) {

        case Activity.RESULT_OK:
        result = "Transmission successful";
        break;
       case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
        result = "Transmission failed";
        break;
       case SmsManager.RESULT_ERROR_RADIO_OFF:
        result = "Radio off";
        break;
       case SmsManager.RESULT_ERROR_NULL_PDU:
        result = "No PDU defined";
        break;
       case SmsManager.RESULT_ERROR_NO_SERVICE:
        result = "No service";
        break;
       }

        Toast.makeText(getApplicationContext(), result,
         Toast.LENGTH_LONG).show();
      }

      }, new IntentFilter(SENT));
     /* Register for Delivery event */
     registerReceiver(new BroadcastReceiver() {

       @Override
      public void onReceive(Context context, Intent intent) {
       Toast.makeText(getApplicationContext(), "Deliverd",
         Toast.LENGTH_LONG).show();
      }

      }, new IntentFilter(DELIVERED));

      /*Send SMS*/
     SmsManager smsManager = SmsManager.getDefault();
     smsManager.sendTextMessage(phoneNo, null, msg, sentPI,
       deliverPI);
    } catch (Exception ex) {
     Toast.makeText(getApplicationContext(),
       ex.getMessage().toString(), Toast.LENGTH_LONG)
       .show();
     ex.printStackTrace();
    }
   }
  });

  }

  @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }

}

Hope this helped !