简体   繁体   English

将数据从应用程序传递到活动

[英]Pass data from Application to the Activity

My android Application class instance is listening to the third-party service for the event. 我的android应用程序类实例正在监听事件的第三方服务。 Then the event is coming out, I need to notice my Activity about it. 然后活动开始了,我需要注意我的活动。 What is the right way to do that? 什么是正确的方法? I know about startActivity() method, but my Activity is running yet! 我知道startActivity()方法,但是我的Activity正在运行!

If the communication is local to your app you can use local broadcasts . 如果通信是您的应用程序本地的,则可以使用本地广播

For communication between components you can also use EventBus (Android-library). 对于组件之间的通信,您还可以使用EventBus (Android-library)。 It is really easy to use and implement (takes less than a minute to understand how it works) and is great in performance. 它非常易于使用和实施(不到一分钟即可了解其工作原理),并且性能出色。

Use Local broadcast events with LocalBroadcastManager - see this tutorial for more information. 通过LocalBroadcastManager使用本地广播事件-有关更多信息,请参阅本教程

I have copied relevant bits of code from the above tutorial for your convenience. 为了方便起见,我已复制了上面教程中的相关代码。

To notify your already running activity about your event, try the following: 要通知您已经在运行的活动有关事件的信息,请尝试以下操作:

  1. Send a broadcast intent from your Application class when you receive the event. 收到事件时,从您的Application类发送广播意图。

     Intent intent = new Intent("my-event"); // add data intent.putExtra("message", "data"); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); 
  2. Register a BroadcastReceiver in your Activity which will handle the received Intents for your event. 在您的活动中注册一个BroadcastReceiver,它将处理您事件的接收到的Intent。 Add the following code to your Activity: 将以下代码添加到您的活动中:

     @Override public void onResume() { super.onResume(); // Register mMessageReceiver to receive messages. LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("my-event")); } // handler for received Intents for the "my-event" event private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Extract data included in the Intent String message = intent.getStringExtra("message"); Log.d("receiver", "Got message: " + message); } }; @Override protected void onPause() { // Unregister since the activity is not visible LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver); super.onPause(); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM