2017-09-02 90 views
2

我了解服务等,因此我的接收器已停止在Android Oreo中工作。接收器在Oreo停止接收

我有这样的代码启动服务 -

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

我有这个在我的服务 -

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); 

但我的接收器永远不会被调用。经过四处搜索,我认为我必须注册我的接收器,但我无法确定如何使用正确的语法对其进行编码。任何人都可以帮忙吗?

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

非常感谢!

UPDATE尝试使用LocalBroadcastManager。

在MainActivity我有 -

BroadcastReceiver mMessageReceiver; 

的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")); 

在我的服务,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); 

这个工程,我看到发送者的消息。

我在做什么错?

+1

接受隐含意图

你仍然可以得到明确的意图和一些特殊的暗示行动,boot_completed或locale_changed例如

更多信息,请给一个[MCVE。 –

+1

清单注册的接收器不能接收隐含的“Intents”的广播。如果你的发送者和接收者在同一个应用程序和同一个进程中,停止使用系统广播('Context“上的'sendBroadcast()'和'registerReceiver()')。相反,使用'LocalBroadcastManager'。这不仅可以让你过去Android 8.0的变化,还可以提高速度和安全性。但是,正如Code-Apprentice所建议的那样,请说明您是如何注册该接收器的。 – CommonsWare

+0

我之前没有注册过接收器......我不认为?但它在奥利奥之前就有效了。我试图通过遵循其他代码来学习,所以只有逐渐了解我在做什么你看到。我试图按照这个 - https://stackoverflow.com/questions/8802157/how-to-use-localbroadcastmanager但我的服务没有上下文,我认为这是为什么它不工作? – AndyCr15

回答