2016-04-04 36 views
0

我正在進行羣聊功能。羣中的每個人都將收到推送(即使是郵件的發件人)。 如果這個人已經打開了該組,即聊天區域是可見的,那麼我希望推送不會顯示在通知欄中,並且它直接更新聊天(我在列表視圖中顯示)。當收到gcm推送通知而不在通知欄中顯示時,動態更新列表視圖

最初的聊天記錄,我從網絡服務中獲得(當用戶打開聊天區)

希望我能夠讓你們清楚什麼我想要實現.thanks提前

回答

4

)首先,當你在的onMessage(得到消息GCMIntentService,送brodcast。像,

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); 

接下來,讓廣播接收器在聊天活動或聊天片段。像,

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()); 
      } 
     } 
    } 
}; 

接下來,在的onCreate()註冊廣播接收器。像

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

接下來,unregisterReceiver的onDestroy()。像,

@Override 
public void onDestroy() { 
    super.onDestroy(); 
    getActivity().unregisterReceiver(appendChatScreenMsgReceiver); 
} 

說明:

1)當GCMIntentService()收到消息,首先,檢查天氣 你在聊天屏幕與否。

2.)如果您正在聊天屏幕中,使用Intent和Broadcast廣播您的消息。

3.)現在,在聊天屏幕上創建您的BroadcastReceiver()。

4.)在onCreate()中註冊您的BroadcastReceiver()並在onDestroy()中取消註冊。

5.)當廣播消息並且您處於聊天屏幕時,此廣播接收器將獲得您的套件。

6.)現在無論你想做什麼。

7.)如果您不在聊天屏幕中,則在通知中顯示受尊敬的消息。不要廣播。

注意:請確定您在哪個屏幕上。

0

我認爲你應該使用觀察者設計模式。 設置一個偵聽器,在其中顯示消息,並在服務中從服務器獲取消息檢查偵聽器,如果偵聽器不是null,則從偵聽器調用更新方法並更新您的列表,否則顯示通知。這個百通的
例如:
http://www.vogella.com/tutorials/DesignPatternObserver/article.html