广播消息 当您从 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 方法执行您的活动更新任务时。