saboehnke saboehnke - 3 months ago 34x
Java Question

onReceive not getting called when SMS data is sent

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);

Here is the code to my sms receiver:

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

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)
if (!currMessage.isStatusReportMessage())
String messageBody = currMessage.getDisplayMessageBody();
byte[] messageBytes = currMessage.getPdu();
int x = 1 + messageBytes[0] + 19 + 7;
myMessage = new String(messageBytes, x, messageBytes.length - x);

Here is what I have in my manifest for the receiver:

<receiver android:name=".DataReceiver">
<action android:name="android.intent.action.DATA_SMS_RECEIVED" />
<data android:scheme="sms" />
<data android:host="localhost" />
<data android:port="8901" />

And here are the permissions I am using:

<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" />


The 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 READ_SMS or SEND_SMS, the 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.