I have a service
public class GcmIntentService extends IntentService{...}
that manages the notifications.
When a notification arrives if the user is out of the application, with a tap on the notification the main activity is resumed and updated
public class MainActivity extends Activity {
...
lv = (ListView) findViewById(R.id.lv);
adapter = new Adapter(this, item);
lv .setAdapter(adapter);
...
}
but how can I update the activity if the user is already on it?
You have to use BroadcastReciever for this task:http://developer.android.com/reference/android/content/BroadcastReceiver.html
in Activity:
public class MainActivity extends Activity {
public static final String NOTIFY_ACTIVITY_ACTION = "notify_activity";
private BroadcastReciver broadcastReciver;
@Override
protected void onStart() {
super.onStart();
broadcastReciver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction.equals(NOTIFY_ACTIVITY_ACTION ))
{
//to do smth
}
}
}
IntentFilter filter = new IntentFilter( NOTIFY_ACTIVITY_ACTION );
registerReceiver(broadcastReciver, filter);
}
@Override
protected void onStop()
{
unregisterReceiver(broadcastReciver);
}
}
In Service:
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(MainActivity.NOTIFY_ACTIVITY_ACTION );
broadcastIntent.putExtra("addtional_param", 1);
broadcastIntent.putExtra("addtional_param2", 2); //etc
sendBroadcast(broadcastIntent);
UPDATE
BTW It's better use LocalBroadcastManager for send broadcast inside the app. It uses the same way as normal broadcast, but first you create LocalBroadcastManager:
LocalBroadcastManager manager = LocalBroadcastManager.getInstance(MainActivity.this);
and in the onStart:
manager.registerReciever(broadcastReciver, filter);
and in the onStop:
manager.unregisterBroadcast(broadcastReciver);
and in the service:
manager.sendBroadcast(broadcastIntent);
if you are using the list and you would like to reload the activity just to refresh the list then, I would suggest you to use following methods on your adatper as soon as some message arrives. This would refresh the content in the list, and list will be updated automatically (without restarting of activity)
adapter.notifyDataSetChanged()
This method notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.
It's not a good option to reload the activity, but if there is no other solution rather than recreating the activity i would suggest to refresh the view itself.
Hope this helps.