Search code examples
androidservicebroadcastreceiverlistener

Broadcast Receiver from service Listener


I created a Broadcast Receiver (BR) in a service that will react to incoming SMS with specific number and body. I only need it to receive for a few seconds/minutes after user action, that's why I didn't registered it in manifest or activity (user may close it). BR has two parts, automatic (which works fine) and manual which should launch MainActivity and start a Dialog. I know that Dialog can't be started from BR and thats why I created a Listener, but my problem is that it is always null after service starts. It has value in onCreate of my MainActivity, but when service starts it changes to null, and I understand why (serivce re-initalize the Listener listener). I even tryed to put initialised listener value to SharedPrefs and restore it after, but when I try to store it with json it only stores null again.
So how do I make my listener != null??? These are the relevant parts of my code:

MainActivity

onCreate {
SMSService smsReceiver = new SMSService();
smsReceiver.setListener(new SMSService.Listener() {   //here listener from service is != null
     @Override
     public void onTextReceived(String s) {
          dialogS(s);           // totaly different dialog
     }
        });

...

mDialogBuilder = new AlertDialog.Builder(this);
...
.setPositiveButton(new OnClick...
       Intent servisIntent = new Intent(MainActivity.this, SMSService.class);
       startService(servisIntent);
...

}

SMSService

private Listener listener;        // and here it get null which is the problem

public int onStartCommand(Intent intent, int flags, int startId) {

...

 SMSReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

Intent i = new Intent(context, MainActivity.class);
context.startActivity(i);
if (listener != null) {
    listener.onTextReceived("4333");
}

}

void setListener(Listener listener) {
        this.listener = listener; }

interface Listener {
        void onTextReceived(String text);
    }

Btw I also tried to put smsReceiver.setListener block of code in my Dialog .setPossitive onClickListener after calling startService hoping it would initiate after service but nothing


Solution

  • Installing a listener mechanism with setter method in service is bad practice. You can use ResultReceiver to receive callback results from service. It is Parcelable, so it can be passed in an intent before service started