Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I found the solution myself. I'm sure that this is not the best way to do it, but at least it works for me.</p> <p>Create a singleton class that derives <code>Handler</code> to store the active <code>ConversationActivity</code>. In the <code>handleMessage</code> method, handle message that will be dispatched from the service that tells the handler to tell the activity to refresh the conversation.</p> <pre><code>public class ActiveMessageHandler extends Handler { private static ActiveMessageHandler _instance = new ActiveMessageHandler(); private Activity _activity = null; @Override public void handleMessage(Message message) { if(message.obj.toString().equals("gcmNewMessage") &amp;&amp; _activity != null) ((ConversationActivity)_activity).repopulateList(); super.handleMessage(message); } public static ActiveMessageHandler instance() { return _instance; } public void setActivity(Activity activity) { _activity = activity; } public Activity getActivity() { return _activity; } } </code></pre> <p>Then, in <code>ConversationActivity</code>, set the activity attribute in the handler.</p> <pre><code>public class ConversationActivity extends Activity { @Override public void onStart() { super.onStart(); ActiveMessageHandler.instance().setActivity(this); } @Override public void onStop() { super.onStop(); ActiveMessageHandler.instance().setActivity(null); } } </code></pre> <p>Finally, in the service, check if the activity in the handler is not null and send a message to the handler to refresh the conversation.</p> <pre><code>public class GCMIntentService extends GCMBaseIntentService { @Override protected void onMessage(Context context, Intent intent) { Bundle extras = intent.getExtras(); String sender = extras.getString("sender"); String message = extras.getString("message"); ConversationModel model = new ConversationModel(context); model.open(); model.createMessage(sender, message.trim(), true, true, ConversationMessage.STATUS_SENT); model.close(); // if ConversationActivity is active, send a message to handler to refresh the conversation if(ActiveMessageHandler.instance().getActivity() != null) { Message msg = Message.obtain(ActiveMessageHandler.instance()); msg.obj = "gcmNewMessage"; ActiveMessageHandler.instance().sendMessage(msg); // Optionally, play a notification sound Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification); r.play(); } else createMessageNotification(context, sender, message); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload