Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receiver stopped receiving in Oreo

I understand services and such are being clamped down on, so my receiver has stopped working in Android Oreo.

I have this code starting the service -

Intent intent = new Intent(this, MyService.class);
intent.putExtra("Time", locationUpdatesTime);
intent.putExtra("Dist", locationUpdatesDistance);
startService(intent);

I have this in my service -

Intent intent = new Intent();
intent.setAction("com.androidandyuk.laptimerbuddy");
intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
intent.putExtra("Lat", thisLat);
intent.putExtra("Lon", thisLon);

sendBroadcast(intent);

But my receiver is never called. Having searched around I think I have to register my receiver, but I can't figure how I code this with the correct syntax. Can anyone help please?

If you wish to downvote me, I'd appreciate if you would comment why, so I can learn as I've looked for an answer, couldn't find/understand it and I think I've laid the question out as I should :-)

Many thanks!

UPDATE Trying to use a LocalBroadcastManager.

In MainActivity I have -

BroadcastReceiver mMessageReceiver;

onCreate I have -

mMessageReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // Get extra data included in the Intent
            String message = intent.getStringExtra("message");
            Log.i("receiver", "Got message: " + message);
        }
    };
    LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("custom-event-name"));

In my service, onLocationChanged

    Log.i("sender", "Broadcasting message");
                Intent intent = new Intent();
                intent.setAction("custom-event-name");
                intent.putExtra("message", "This is my message!");

 LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);

This works as I see the sender message.

What am I doing wrong?

like image 631
AndyCr15 Avatar asked Jan 04 '23 12:01

AndyCr15


1 Answers

Since Android Oreo, receivers must be registered in runtime using context.registerReceiver(receiver, intentFilter); to receive implicit intents

You can still receive explicit intents and some special implicit actions, as boot_completed or locale_changed for example

More information at https://developer.android.com/about/versions/oreo/background.html#broadcasts

like image 172
Simone S. Avatar answered Jan 06 '23 02:01

Simone S.