1

我有一个简单的消息应用程序。它使用 STOMP over Websockets 从服务器接收数据(消息)。

我想将所有 websockets 东西移动到我可以绑定到我的活动以通过它发送消息的服务。

使用 Binder,我可以在 Activity 中运行 Service 方法,因此发送消息不是问题。问题是接收消息并将它们放到 Activity 的视图中。

我想用本地数据库做到这一点,就像这样:

  1. 服务从 STOMP 接收消息
  2. 服务将该消息放入本地数据库
  3. Activity 以某种方式了解数据库中有新消息并将其放入 ListView(使用 CursorAdapter?)。

我怎样才能做到这一点?也许我需要在 Activity 和 Service 中使用 SAME 数据库 ContentResolver 之类的东西?

4

1 回答 1

0

广播消息 当您从 websocket 收到消息时。因此,从您的服务中调用此方法。

private void broadcastNotification(Context context){
    Intent intent = new Intent("NOTIFICATION");
    intent.putExtra("MESSAGE", "your_message");
    context.sendBroadcast(intent);        
}

在您的活动中注册广播接收器。

@Override
protected void onResume() {
    super.onResume();
    mContext.registerReceiver(mMessageReceiver, new   IntentFilter("NOTIFICATION"));
}

@Override
protected void onPause() {
    stopService();
    mContext.unregisterReceiver(mMessageReceiver);
    super.onPause();
}

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        //Update the Activity
    }
}

因此,每当您从 websocket 接收消息时,将其存储到数据库并广播消息并在活动中收听它。当您的活动调用中的 OnReceive 方法执行您的活动更新任务时。

于 2015-04-14T15:41:11.050 回答