收到gcm推送通知时动态更新listview而不在通知栏中显示

kar*_*ran 0 android listview push google-cloud-messaging

我具有群组聊天功能。群组中的每个人都会收到推送(甚至消息的发件人)。如果该人已打开该组,即可见聊天区域,则我希望该推送不显示在通知栏中,并且它直接更新聊天(我在列表视图中显示)。

最初,我是从Web服务获得聊天记录的(当用户打开聊天区域时)

希望我能够让你们清楚我想要实现的目标。

Har*_*tel 5

首先,当您在GCMIntentService的onMessage()中获取消息时,发送广播。喜欢,

Intent i = new Intent();
                            i.setAction("appendChatScreenMsg");
                            i.putExtra("sender_id", b.getString("sender_id"));
                            i.putExtra("message", b.getString("message"));
                            i.putExtra("time", getCurrentTime());
                            i.putExtra("date", getCurrentDate());
                            this.sendBroadcast(i);
Run Code Online (Sandbox Code Playgroud)

接下来,在您的聊天活动或聊天片段中设置BroadcastReceiver。喜欢,

BroadcastReceiver appendChatScreenMsgReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle b = intent.getExtras();
        if (b != null) {
            int totalItems = adapter.getCount() - 1;


                ChatModel model = new ChatModel("" + sharedPreferences.getString(VariableBag.USERID, ""), ""+ b.getString("sender_id"), "" + b.getString("message"), b.getString("date"), b.getString("time"));
                arrChat.add(model);


            if (adapter != null) {

                if (lstChat.getLastVisiblePosition() == totalItems) {
                    adapter.notifyDataSetChanged();
                    lstChat.setSelection(adapter.getCount());
                } else {
                    adapter.notifyDataSetChanged();
                }
            } else {
                adapter = new ChatAdapter(getActivity());
                lstChat.setAdapter(adapter);
                adapter.notifyDataSetChanged();
                lstChat.setSelection(adapter.getCount());
            }
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

接下来,在onCreate()中注册BroadcastReceiver。喜欢

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getActivity().registerReceiver(this.appendChatScreenMsgReceiver, new IntentFilter("appendChatScreenMsg"));
}
Run Code Online (Sandbox Code Playgroud)

接下来,在onDestroy()中取消注册接收器。喜欢,

@Override
public void onDestroy() {
    super.onDestroy();
    getActivity().unregisterReceiver(appendChatScreenMsgReceiver);
}
Run Code Online (Sandbox Code Playgroud)

说明:

1.)在GCMIntentService()中收到消息后,首先,请检查您是否在聊天屏幕中。

2.)如果您在聊天屏幕中,请使用“意图和广播”广播您的消息。

3.)现在,在聊天屏幕中创建您的BroadcastReceiver()。

4.)在onCreate()中注册您的BroadcastReceiver(),然后在onDestroy()中注销。

5.)当广播消息并且您处于聊天屏幕时,此广播接收者将获得您的捆绑包。

6.)现在,无论您想做什么。

7.)如果您不在聊天屏幕中,则在通知中显示受尊重的消息。不要广播。

注意:请确保您当前在哪个屏幕上。