Search code examples
android-serviceandroid-notificationsandroid-internet

Extras Sent in a Pending Intent through a Notification are not changed even with new notifications until I terminate the service


I have an application composed of 2 parts

1-a sequence of activities. (Login, Then Dashboard, Then a feed). 2-a background service driven by a push server.

every time the the service receives a push, creates a notification with a pending Intent this Intent adds string extras received from the push server example: adds a character "N" or "R"

now after installing the service application and after the first run the extras are sent in the intent correctly but every subsequent time a server sends a message to the application through an intent the extras aren't changed i.e.

if the First Message sends "N" then all the subsequent Messages will send "N".

Since the description above is too complicated I'll give you snippets of my code:

This is the code in the service that Creates a notification with a pending Intent

    Notification n = new Notification();            
    n.flags |= Notification.FLAG_SHOW_LIGHTS;
    n.flags |= Notification.FLAG_AUTO_CANCEL;
    n.defaults = Notification.DEFAULT_ALL;      
    n.when = System.currentTimeMillis();
    // The following line displays N or R depending on the message received . 
    Log.d("Received Type: ",text.substr(0,1); // Example "N" from: "N|Notification Text"

    n.icon = R.drawable.notification_icon;
    Intent i = new Intent(this, MyActivity.class);
    i.putExtra("type", text.substr(0,1);
i.putExtra("text", text.substr(2);
    PendingIntent pi = PendingIntent.getActivity(this, 0, i , 0);
    n.setLatestEventInfo(this, NOTIF_TITLE, "Notification: " + text.substring(2), pi);

Now this is the activity that receives the Data from the intent

    super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout);
activeWebview  = (WebView) findViewById(R.id.webview);

Intent sender=getIntent();
type = sender.getStringExtra("type");   // Assume this is defined somewhere
text = sender.getStringExtra("text");   // Assume this is defined somewhere
    Log.d( "Type received:" , type );  // This everytime displays "N" 

My problem is that the Extras Sent in the intent are the same everytime a new notification is received it never changes unless I terminate the application and the service and start it again.

As if it's saved somewhere in the memory and I need to clean it


Solution

  • You need to add the flags in your pending intent:

    PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_UPDATE_CURRENT
    
    PendingIntent pi = PendingIntent.getActivity(this, 0 , i , PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_UPDATE_CURRENT);
    

    Otherwise the extras won't get updated. http://developer.android.com/reference/android/app/PendingIntent.html#FLAG_CANCEL_CURRENT