接收器停止在奥利奥接收

And*_*r15 3 android broadcastreceiver

我理解服务等因此受到限制,因此我的接收器已停止在Android Oreo中工作.

我有这个代码启动服务 -

Intent intent = new Intent(this, MyService.class);
intent.putExtra("Time", locationUpdatesTime);
intent.putExtra("Dist", locationUpdatesDistance);
startService(intent);
Run Code Online (Sandbox Code Playgroud)

我在我的服务中有这个 -

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);
Run Code Online (Sandbox Code Playgroud)

但我的接收器从未被调用过.搜索过后,我想我必须注册我的接收器,但我无法弄清楚我是如何使用正确的语法对其进行编码的.有人可以帮忙吗?

如果你想投票给我,我会很感激,如果你会评论为什么,所以我可以学习,因为我找到了答案,找不到/理解它,我想我已经提出了问题,因为我应该:-)

非常感谢!

更新尝试使用LocalBroadcastManager.

在MainActivity我有 -

BroadcastReceiver mMessageReceiver;
Run Code Online (Sandbox Code Playgroud)

onCreate我有 -

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"));
Run Code Online (Sandbox Code Playgroud)

在我的服务中,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);
Run Code Online (Sandbox Code Playgroud)

这是因为我看到发件人消息.

我究竟做错了什么?

小智 7

从Android Oreo开始,接收器必须使用context.registerReceiver(receiver,intentFilter)在运行时注册; 接收隐含意图

您仍然可以接收显式意图和一些特殊的隐式操作,例如boot_completed或locale_changed

有关更多信息,访问https://developer.android.com/about/versions/oreo/background.html#broadcasts