Search code examples
androidbroadcastreceiverandroid-broadcastandroid-intentservice

Android pass message from IntentService to Activity


I IntentService that I would like to send message to the main Activity it is nested in. I am using a broadcast receiver to broadcast the message I got from the IntentService as such:

public static class ResponseReceiver extends BroadcastReceiver {
        public static final String ACTION_RESP = "com.mypackage.intent.action.MESSAGE_PROCESSED";
        @Override
        public void onReceive(Context context, Intent intent) {
            String text;
            text = intent.getStringExtra(RegistrationIntentService.PARAM_OUT);
            regid = text;
        }
    }

I have registered the receiver in the Oncreate method of the main Activity. How can I send the "text" in this case? It is weird that regid in this case is null while "text" has the string data I wanted.


Solution

  • When registering, this was what worked for me

    IntentFilter filter = new IntentFilter(ResponseReceiver.ACTION_RESP);
            filter.addCategory(Intent.CATEGORY_DEFAULT);
            receiver = new ResponseReceiver();
    
            LocalBroadcastManager.getInstance(this).registerReceiver(receiver, filter);
    

    as opposed to

    registerReceiver(receiver, filter);
    
    @Override
            public void onReceive(Context context, Intent intent) {
                final String text = intent.getStringExtra(RegistrationIntentService.PARAM_OUT);
    
                button.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //access the string text and send it to backend
                    }
                });
            }
    

    I hope this will help someone. Sending the string like suggested in the comments didn't work for me. I was getting nullpointerexception at that specific line where I assigned ma.regid = text;