'ForegroundService that waits for incoming SMS in Android

I do not really know how to tackle my problem.

I start a Foreground service in Android. Within that service I wait for 2 minutes and now I would like to listen to incoming SMS. If within 2 minutes no incoming SMS is received, I would like to have a text to speech message.

My Foreground service is running perfectly so far, however, I do not know how to tackle the problem if no SMS is received or is received?

First, I thought about sending a Broadcastreceiver manually, then waiting for 2 minutes and if within those 2 minutes an SMS is received, everything is fine.

However, I would like to react to an incoming SMS immediately and I do not know how to do that!

Maybe someone can point me to the right solution?

Here is my code for the Foreground service:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    loadSharedPreferences(StaticFields.WAIT_MINUTES);
    createNotificationChannel();
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this,
            0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT |
                    PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE);
    notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
            .setContentTitle("No SMS retrieved within the last " + counter + " seconds")
            .setContentIntent(pendingIntent)
            .setOngoing(true)
            .setOnlyAlertOnce(true)
            .setSmallIcon(R.drawable.ic_launcher_background);

    notification = notificationBuilder.build();

    startForeground(NOTIFICATION_ID, notification);

    waitForXMinutes*=60;
    while (counter <= waitForXMinutes) {
        try {
            Thread.sleep(1000);
            manager.notify(NOTIFICATION_ID /* ID of notification */,
                    notificationBuilder.setContentTitle("No parkingticket for " + counter + " seconds").build());
            counter++;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    stopSelf();
    return START_NOT_STICKY;
}

Thank you very much in advance!



Solution 1:[1]

For the moment I solved the problem with the BroadcastReceiver but not the problem with the not receiving SMS.

If no SMS is received at all, a voice message should be played!

Here is my code. Within the service I created the BroadcastReceiver

private final BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if(action.equals("android.provider.Telephony.SMS_RECEIVED")){
            Bundle bundle = intent.getExtras();
            SmsMessage[] msgs = null;
            String msg_from;
            if (bundle != null){
                try{
                    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]);
                        msg_from = msgs[i].getOriginatingAddress();
                        String msgBody = msgs[i].getMessageBody();
                        if(!msgBody.contains("Zuletzt gebuchter Parkschein")) {
                            textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
                                @Override
                                public void onInit(int status) {
                                    if (status != TextToSpeech.ERROR) {
                                        textToSpeech.setLanguage(Locale.GERMAN);
                                        textToSpeech.speak("Es wurde kein Parkschein in den letzten " + waitForXMinutes + " Sekunden gebucht",
                                                TextToSpeech.QUEUE_FLUSH, null, "0");
                                    }
                                }
                            });
                        }
                    }
                }catch(Exception e){
                    Log.d("Exception caught",e.getMessage());
                }
            }
        }
    }
};

And in the onCreate method I registered the BroadcastReceiver

@Override
public void onCreate() {
    super.onCreate();
    filter = new IntentFilter();
    filter.addAction("android.provider.Telephony.SMS_RECEIVED");

    registerReceiver(receiver, filter);
}

Still pending is my problem, if no SMS is received at all. I am still looking for a solution where my "internal" Broadcastreceiver gets triggered all the time, even if no SMS is received.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1