接收器停止在Oreo中接收 [英] Receiver stopped receiving in Oreo
问题描述
我了解服务,并且此类服务受到限制,因此我的接收器已停止在Android 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 :-)
非常感谢!
更新。尝试使用LocalBroadcastManager。
UPDATE Trying to use a LocalBroadcastManager.
在MainActivity中,我有-
In MainActivity I have -
BroadcastReceiver mMessageReceiver;
onCreate我有-
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"));
在我的服务中,onLocationChanged
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.
我在做什么错?
推荐答案
自Android Oreo以来,必须在运行时使用context.registerReceiver(receiver注册接收者,intentFilter);接收隐式意图
Since Android Oreo, receivers must be registered in runtime using context.registerReceiver(receiver, intentFilter); to receive implicit intents
您仍然可以接收显式意图和一些特殊的隐式动作,例如boot_completed或locale_changed
You can still receive explicit intents and some special implicit actions, as boot_completed or locale_changed for example
有关更多信息,请访问 https://developer.android.com/about/版本/oreo/background.html#broadcasts
More information at https://developer.android.com/about/versions/oreo/background.html#broadcasts
这篇关于接收器停止在Oreo中接收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!