1

I am writing an app, which should work even after the app is closed. Here is the code which I wrote to accept the incoming SMS.

public class SMSReceiver extends BroadcastReceiver {

    private ResultReceiver receiver;
    private Context context;

    @Override
    public void onReceive(Context context, Intent intent) {
        this.context = context;

        // Parse the SMS.
        Bundle bundle = intent.getExtras();
        SmsMessage[] msgs = null;
        String str = "";
        if (bundle != null)
        {
            // Retrieve the SMS.
            Object[] pdus = (Object[]) bundle.get("pdus");
            msgs = new SmsMessage[pdus.length];
            for (int i=0; i<msgs.length; i++)
            {
                msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);

                str += "SMS from " + msgs[i].getOriginatingAddress();
                str += " :\n";
                str += " :\n";
                str += "MessageBody: ";
                str += msgs[i].getMessageBody();

            }
            Log.i("SmsReceiver message := " + str);
        }
    }
}

I had registered this Broadcast, in the my main activity. and I am not unregistering broadcast.

This works when my App is launched, but doesn't work when app is closed.

How can I receive SMS even after the app is closed? Any help is appreciated.

Thanks

George Brighton
  • 5,131
  • 9
  • 27
  • 36
User12111111
  • 1,179
  • 1
  • 19
  • 41

3 Answers3

3

You can have the receiver run as a Service. Here is the code I use:

public class Communicator extends Service
{

private final String TAG = this.getClass().getSimpleName();

private SMSReceiver mSMSreceiver;
private IntentFilter mIntentFilter;

@Override
public void onCreate()
{
    super.onCreate();


    Log.i(TAG, "Communicator started");
    //SMS event receiver
    mSMSreceiver = new SMSReceiver();
    mIntentFilter = new IntentFilter();
    mIntentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
    mIntentFilter.setPriority(2147483647);
    registerReceiver(mSMSreceiver, mIntentFilter);

    Intent intent = new Intent("android.provider.Telephony.SMS_RECEIVED");
    List<ResolveInfo> infos = getPackageManager().queryBroadcastReceivers(intent, 0);
    for (ResolveInfo info : infos) {
        Log.i(TAG, "Receiver name:" + info.activityInfo.name + "; priority=" + info.priority);
    }
}

@Override
public void onDestroy()
{
    super.onDestroy();

    // Unregister the SMS receiver
    unregisterReceiver(mSMSreceiver);
}

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

private class SMSReceiver extends BroadcastReceiver
{
    private final String TAG = this.getClass().getSimpleName();

    @Override
    public void onReceive(Context context, Intent intent)
    {
        Bundle extras = intent.getExtras();


        String strMessage = "";

        if ( extras != null )
        {
            Object[] smsextras = (Object[]) extras.get( "pdus" );

            for ( int i = 0; i < smsextras.length; i++ )
            {
                SmsMessage smsmsg = SmsMessage.createFromPdu((byte[])smsextras[i]);

                String strMsgBody = smsmsg.getMessageBody().toString();
                String strMsgSrc = smsmsg.getOriginatingAddress();

                strMessage += "SMS from " + strMsgSrc + " : " + strMsgBody;                    


                if (strMsgBody.contains(Constants.DELIMITER)) {

                    Intent msgIntent = new Intent(Constants.INTENT_INCOMMING_SMS);
                    msgIntent.putExtra(Constants.EXTRA_MESSAGE, strMsgBody);
                    msgIntent.putExtra(Constants.EXTRA_SENDER, strMsgSrc);
                    sendBroadcast(msgIntent);

                    this.abortBroadcast();
                }
            }



        }

    }

}
}

Remember to add it to the manifest:

<service android:name="yourpakage.Communicator" />

Now you can start listening for incomming SMS messages by starting the service:

startService(new Intent(this, Communicator.class));

I stop the service in onDestroy of my Activity but I suppose you can keep it running and even register it to be started when the device is booted as with any other service.

Here is the code to stop the service:

stopService(new Intent(this, Communicator.class));

In case you also want to send SMS at some point I have made a rather extensive answer on the subject here: Send SMS until it is successful

Community
  • 1
  • 1
cYrixmorten
  • 7,110
  • 3
  • 25
  • 33
  • As per the Android document, the service will be force close when memory is low. http://developer.android.com/guide/components/services.html With this, I may be loosing the incoming SMS. Is there any other way to do this? – User12111111 Nov 07 '13 at 07:04
  • This is the best that I can come up with. You are right that android can close it but I truly think it to be unlikely as it does not take up any memory or CPU. So in case it get low on memory, another app or service will be destroyed, I think. – cYrixmorten Nov 07 '13 at 07:13
  • If you, instead of starting the service in code, register the the service on boot, I believe you get all the SMS messages. That is, if not intercepted and stopped by another app such as GoSMS or Handcent – cYrixmorten Nov 07 '13 at 07:19
  • I registered broadcast receiver in Manifest file and receive sms messages at port 5005, but there are other Apps which are listening to incoming sms messages too, in this case, it creates conflict and cause my app to show unrelated toast messages which I don't know which app cause this and why is this happening? Is it related to port number? – Davoud Feb 15 '17 at 06:24
  • @Patzu Not sure I understand. But worth noting that this is a rather old answer, and blocking other apps from receiving the sms using `this.abortBroadcast()` is no longer possible. – cYrixmorten Feb 16 '17 at 14:02
1

receiver should be in manifest; also keep in mind that you don't have a guarantee to receive SMS even with declared receiver's highest priority - other installed apps which happened to receive SMS Intent from OS may cancel further Intent propagation

jmuet
  • 386
  • 6
  • 12
0

If you registering you receiver in activity you must unregister it! It's very important to avoid memory leaks.

If you want to receive sms at any time you must registet it in AndroidManifest file

Alexander Mikhaylov
  • 1,790
  • 1
  • 13
  • 23