如何在片段和非父活动之间传输数据?

时间:2018-02-10 10:36:15

标签: android firebase android-activity android-fragmentactivity

我很难解决这个问题

enter image description here

我正在从会话列表片段

中侦听数据

现在如何在聊天时在聊天活动中发送收到的数据?请帮忙。

2 个答案:

答案 0 :(得分:2)

如果我正确地解决了问题,这似乎是EventBus的工作。看看如何在这里实现它:http://square.github.io/otto/

首先,您需要定义一个事件

public class ChatMessage{
   private String status,message,sender;
   //with constructors and toString
}

在您的聊天活动中,您可以在活动总线上发布活动,例如

EventBus.getDefault().post(new ChatMessage(status,message,sender)

在“对话”列表中(假设您正在显示由适配器管理的列表或Recyclerview),请使适配器知道您的事件总线

@Subscribe(threadMode = ThreadMode.MAIN)
public void updateAdapter(ChatMessage message) {
    //here you should get the chat item and update it
    //do not forget to call notifyDatasetChanged() at the end to update your adapter
}

在您希望更新对话列表片段的任何时候(例如,当消息传入时,当您向联系人发送消息时)向EventBus发送消息

如果您可以从片段/活动中提供额外的代码并形成适配器,我将更新我的答案。

答案 1 :(得分:2)

ChattingActivity是一个单独的Activity,需要BroadcastReceiver来收听ConversationListFragment中收到的新聊天消息。

设置BroadcastReceiver的实现非常简单。以此为例。 ChattingActivity将包含这些内容。

@Override
public void onCreate(Bundle savedInstanceState) {

  // Other code ...

  // Register to receive messages.
  // We are registering an observer (mMessageReceiver) to receive Intents
  // with actions named "new-chat-message".
  LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
      new IntentFilter("new-chat-message"));
}

// Our handler for received Intents. This will be called whenever an Intent
// with an action named "new-chat-message" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    // Get extra data included in the Intent
    String message = intent.getStringExtra("message");
    Log.d("receiver", "New chat message received: " + message);
  }
};

@Override
protected void onDestroy() {
  // Unregister since the activity is about to be closed.
  LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
  super.onDestroy();
}

现在,当使用相同的主题名称收到新的聊天消息时,ConversationListFragment应相应地发送广播。我们假设ConversationListFragment中的函数是onNewMessageReceived。函数的参数newMsg,它是应用程序在ConversationListFragment中收到的消息。

// Send an Intent with an action named "new-chat-message". The Intent sent should 
// be received by the ChattingActivity.
private void onNewMessageReceived(String newMsg) {
  Log.d("sender", "Broadcasting new chat message");
  Intent intent = new Intent("new-chat-message");
  // You can also include some extra data.
  intent.putExtra("message", newMsg);
  LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

您也可以考虑传递其他参数。例如,收到其他会话的新消息,该消息目前未在ChattingActivity中打开。因此,在这种情况下不应更新ChattingActivity。所以我们应该发送一个标志,例如otherPartyAccountId,表明我正在聊天的人。因此,如果ChattingActivity与某人打开,但是收到了另一个人的消息,则不应更新当前的ChattingActivity

我建议将ChattingActivity打开为Fragment下的另一个HostingActivity。这将使整个过程流程大大简化。