从服务更新数据库,然后处理活动中的更改 - 如何?

时间:2015-04-14 15:33:17

标签: android android-service android-sqlite android-service-binding

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

我想将所有的websockets内容移动到Service,我可以绑定到我的活动以通过它发送消息。

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

我想用本地数据库这样做:

  1. 服务从STOMP接收消息
  2. 服务将该消息放入本地数据库
  3. Activity以某种方式理解数据库中有新消息并将其放入ListView(使用CursorAdapter?)。
  4. 我怎样才能实现这一目标?也许我需要在Activity和服务中使用SAME数据库ContentResolver?

1 个答案:

答案 0 :(得分: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方法执行您的活动更新任务时。