I am creating an app on android that needs to be able to allow android devices to send SMS data back and forth with SmsManager.sendDataMessage(). For some reason when I try to send data this way my sms receiver doesn't ever get anything. What am I missing?
Here is the code to send the data:
SmsManager sm = SmsManager.getDefault();
sm.sendDataMessage(toPhone, null, (short)8901, message.getBytes(), null, null);
public class DataReceiver extends BroadcastReceiver
private String myMessage;
public void onReceive(Context context, Intent intent)
Bundle bundle = intent.getExtras();
if (bundle == null) return;
Object objs = (Object) bundle.get("pdus");
SmsMessage messages = new SmsMessage[objs.length];
for (int i = 0; i < objs.length; i++)
messages[i] = SmsMessage.createFromPdu((byte) objs[i]);
for (SmsMessage currMessage : messages)
String messageBody = currMessage.getDisplayMessageBody();
byte messageBytes = currMessage.getPdu();
int x = 1 + messageBytes + 19 + 7;
myMessage = new String(messageBytes, x, messageBytes.length - x);
<action android:name="android.intent.action.DATA_SMS_RECEIVED" />
<data android:scheme="sms" />
<data android:host="localhost" />
<data android:port="8901" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
RECEIVE_SMS permission is required to receive data SMS, too. If your app is running under Marshmallow or above, and the
targetSdkVersion is 23 or greater, you'll need to request this permission at runtime, as well.
Even if you're already requesting other SMS permissions, you still need to specifically request
RECEIVED_SMS. Your app is granted only those permissions it requests, and though the SMS group is presented when asking for
RECEIVED_SMS will not be granted unless it's included in the request.
It should also be noted that this permission must be in place before the app is to receive data messages. You cannot request permissions from a Receiver, and, by that time, it will have been far too late anyway. Your Receiver would never even know there was a message. Simply add that permission to the request for the rest of the SMS permissions.