简体   繁体   English

通过后台活动的事件更新活动

[英]Update an activity by events of a background activity

I have 2 activities A and B. A has a recyclerView with list of songs.我有 2 个活动 A 和 B。A 有一个带有歌曲列表的 recyclerView。 When i click one command goes to B and it starts playing it.当我单击一个命令到 B 时,它开始播放它。 B has an onCompletionListener() so it changes and plays song automatically. B 有一个onCompletionListener()所以它会自动改变和播放歌曲。 When one hovers back to activity A, name of currently playing song is displayed in a textView there.当悬停回到活动 A 时,当前播放歌曲的名称会显示在那里的 textView 中。 Problem is that when a song is is changed in background, the textView can't be automatically updated.问题是在后台更改歌曲时,无法自动更新 textView。 One solution I had thought is making that textView static and change it from OnCompletionListener in B but I don't find that efficient.我曾想过的一种解决方案是将 textView 设为静态并从 B 中的 OnCompletionListener 更改它,但我认为效率不高。 Is there a better way of doing that.有没有更好的方法来做到这一点。

There are several ways to implement this:有几种方法可以实现这一点:

  • Handler You can implement Handler in A and pass the address of Handler to B. And you can send message to A using this Handler. Handler 你可以在 A 中实现 Handler 并将 Handler 的地址传递给 B,然后你就可以使用这个 Handler 向 A 发送消息。
  • BroadcastReceiver Same as Handler. BroadcastReceiver 与 Handler 相同。 You can implement in A and pass the address of BroadcastReceiver to B. And you can send broadcast to B using this.您可以在 A 中实现并将 BroadcastReceiver 的地址传递给 B。您可以使用它向 B 发送广播。
  • startActivityForResult You can start activity B by using startActivityForResult. startActivityForResult 您可以使用 startActivityForResult 启动活动 B。 You need to implement onActivityResult function in A. You can send data to A when B is finished.你需要在 A 中实现 onActivityResult 函数,你可以在 B 完成后向 A 发送数据。 You can send last song data to A when B is finishing.当 B 完成时,您可以将最后一首歌曲数据发送给 A。

If you're newbie in Android, the easiest (and fastest) way to create a communication channel between Android components is using a bus like EventBus如果您是 Android 新手,在 Android 组件之间创建通信通道的最简单(也是最快)的方法是使用EventBus 之类的总线

You just have to create a class containing the informations, then your activities will subscribe to a bus and they will send and receive these objects each other very easily您只需要创建一个包含信息的类,然后您的活动将订阅总线,并且它们将非常容易地相互发送和接收这些对象

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

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