-2

I want to create an application that listen to sms and always run in the background.

The service must start when the user turn his android on - and always in action until the android device is down.

I know only how to create application with GUI ( with activity ) - but on this case i don't want to have any GUI with it.

I don't find any example of how to do it.

Mattias Isegran Bergander
  • 11,811
  • 2
  • 41
  • 49
Yanshof
  • 9,659
  • 21
  • 95
  • 195
  • 2
    You can create a broadcast receiver to receive the action boot_completed and inside the receiver, you can start the service. – Nigam Patro Mar 12 '16 at 13:39
  • 3
    "I don't find any example of how to do it." - I'm sorry, but, really?!? Have you tried searching Stack Overflow, specifically? – Mike M. Mar 12 '16 at 13:39
  • @Nigam Patro - but i can do it without having any Activity ? because i do'nt want to have any GUI – Yanshof Mar 12 '16 at 13:41
  • 1
    I said about receiver, I didn't said about any activity. – Nigam Patro Mar 12 '16 at 13:42
  • @ Nigam Patro - sorry .. i know only about how to create application with activity. So, in this case - how i creating app without having any activity ? – Yanshof Mar 12 '16 at 13:44

1 Answers1

2

If you only need to react to incoming sms, you can just register a broadcast receiver for that. No special background service needed. Your code will be called whenever a SMS is received.

In your android manifest point out a java class that extends BroadcastReceiver to be called for incoming SMS:

<receiver android:name="mypackage.SmsReceiver">   
            <intent-filter>
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
            </intent-filter>
</receiver>

Don't forget the permission:

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

And then implement your SmsReceiver class:

public class SmsReceiver extends BroadcastReceiver {
    private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (ACTION.equals(action)) {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                Object messages[] = (Object[]) bundle.get("pdus");
                if (messages != null) {
                    SmsMessage smsMessages[] = new SmsMessage[messages.length];
                    for (int n = 0; n < messages.length; n++) {
                        smsMessages[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
                        SmsMessage smsMessage = smsMessages[n];
                        String from = smsMessage.getOriginatingAddress();
                        //do your thing
                    }
                }
            }
        }
    }
}
Mattias Isegran Bergander
  • 11,811
  • 2
  • 41
  • 49