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?
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
create your intent than pass in method
sendImplicitBroadcast(this,new Intent(IntentActions.ACTION_APP_CREATE));
Static Method
public static void sendImplicitBroadcast(Context ctxt, Intent i) {
PackageManager pm=ctxt.getPackageManager();
List<ResolveInfo> matches=pm.queryBroadcastReceivers(i, 0);
for (ResolveInfo resolveInfo : matches) {
Intent explicit=new Intent(i);
ComponentName cn=
new ComponentName(resolveInfo.activityInfo.applicationInfo.packageName,
resolveInfo.activityInfo.name);
explicit.setComponent(cn);
ctxt.sendBroadcast(explicit);
}
}
来源:https://stackoverflow.com/questions/46015332/receiver-stopped-receiving-in-oreo