'How to sennd a broadcast from a background service?

I have a service from where I want to send a broadcast using:

public class BackgroundService extends Service {
    public BackgroundService() {
        Log.i(MainActivity.TAG, "Background service started");
        Intent broadcastIntent = new Intent("android.intent.action.CUSTOM_INTENT");
        sendBroadcast(broadcastIntent);
    }

The service is started from the Main Activity like so:

 public void buttonClick(View view) {
        Intent serviceIntent = new Intent(this, BackgroundService.class);
        startService(serviceIntent);
    }

However this does not work, it shows this error:

.BackgroundService: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.content.Context.sendBroadcast(android.content.Intent)' on a null object reference

Can anyone point out why? or provide a working example?

Thanks



Solution 1:[1]

You can do this with localBroadcastReceiver like below in service

val intent = Intent()
intent.setAction(YOUR_ACTION_STRING)
LocalBroadcastManager.getInstance(context).sendBroadcast(intent)

and on activity write below code

intentFilter.addAction(YOUR_ACTION_STRING);
LocalBroadcastManager.getInstance(context).registerReceiver(yourReceiver, intentFilter)

and yourReceiver param extends from broadcastReceiver

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 sajadab