User12111111
User12111111

Reputation: 1219

android: receive sms even if app is closed

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

Upvotes: 1

Views: 3995

Answers (3)

cYrixmorten
cYrixmorten

Reputation: 7108

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

Upvotes: 3

jmuet
jmuet

Reputation: 396

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

Upvotes: 1

Alexander Mikhaylov
Alexander Mikhaylov

Reputation: 1800

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

Upvotes: 0

Related Questions