Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open new activity on click of push notification?

I am developing an android application in which I need to receive multiple notifications, each containing unique data.

Things I have already accomplished 1. Receive multiple notifications using the gcm service 2. Display the data send by the server on clicking the notification in a new activity

The problem: Suppose I have received three notifications, each with unique data. When I click on one notification a new activity starts with the data in that notification. So now the receive notification activity is running. Now if I click on the second notification receive notification activity loads with the old data(the one from first notification). If I close the application and click on the third notification the receive notification activity loads with data from the third notification as it is suppossed to.

I have tried:

  1. Setting the intent flag to FLAG_ACTIVITY_CLEAR_TOP(not working)
  2. Edited the manifest file to include android:launchMode="singleInstance" without any success

I am using

resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

In intentservice and add android:launchMode="singleInstance" in manifest file both are not working.

intentservice class

public class GcmIntentService extends IntentService{

Context context;
public static int notify_no=0;

//System.currentTimeMillis();

private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public static final String TAG = "GCM NOTIFICATION";

public GcmIntentService() {
    super("GcmIntentService");
    // TODO Auto-generated constructor stub
}

@Override
protected void onHandleIntent(Intent intent) {
    // TODO Auto-generated method stub
    Bundle extras = intent.getExtras();
    String msg = intent.getStringExtra("message");
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    String messageType = gcm.getMessageType(intent);


     if (!extras.isEmpty()) {

         if (GoogleCloudMessaging.
                    MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
               // sendNotification(RegIdDTO.REG_ID,"Send error: " + extras.toString());
             sendNotification(this,msg);
            } else if (GoogleCloudMessaging.
                    MESSAGE_TYPE_DELETED.equals(messageType)) {
               // sendNotification(RegIdDTO.REG_ID,"Deleted messages on server: " +
               //         extras.toString());
                sendNotification(this,msg);
            // If it's a regular GCM message, do some work.
            } else if (GoogleCloudMessaging.
                    MESSAGE_TYPE_MESSAGE.equals(messageType)) {
                // This loop represents the service doing some work.
                for (int i=0; i<5; i++) {
                    Log.i(TAG, "Working... " + (i+1)
                            + "/5 @ " + SystemClock.elapsedRealtime());
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                    }
                }
                Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
                // Post notification of received message.
                //sendNotification("Received: " + extras.toString());
               // sendNotification(RegIdDTO.REG_ID,msg);
                sendNotification(this,msg);
                Log.i(TAG, "Received: " + extras.toString());
            }
        }
     GcmBroadcastReceiver.completeWakefulIntent(intent);
}


private static void sendNotification(Context context,String message) {
    int icon = R.drawable.ic_stat_gcm;
    long when = System.currentTimeMillis();
    NotificationCompat.Builder nBuilder;
    Uri alarmSound = RingtoneManager
            .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    nBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("header")
            .setLights(Color.BLUE, 500, 500).setContentText(message)
            .setAutoCancel(true).setTicker("Notification from Traffic")
            .setVibrate(new long[] { 100, 250, 100, 250, 100, 250 })
            .setSound(alarmSound)
            ;

    String consumerid = null;
    Integer position = null;
           // write your click event here
       Intent resultIntent = new Intent(context, NotificationReceiveActivity.class);

       resultIntent.putExtra("message", message);
      // resultIntent.setData(Uri.parse("content://"+when));
       resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

 PendingIntent resultPendingIntent = PendingIntent.getActivity(context,
        notify_no, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        // Show the max number of notifications here
  if (notify_no < 9) {
    notify_no = notify_no + 1;
  } else {
    notify_no = 0;
  }
nBuilder.setContentIntent(resultPendingIntent);
NotificationManager nNotifyMgr = (NotificationManager) context
        .getSystemService(context.NOTIFICATION_SERVICE);
  nNotifyMgr.notify(notify_no + 2, nBuilder.build());
  }

}

Receive activity

public class NotificationReceiveActivity extends Activity {

    TextView name;
    TextView deal;
    TextView valid;
    TextView address;
    JSONObject json;
    GcmIntentService serv;
    Context mContext;
  //  static boolean active = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_notification_receive);


    Intent intent = getIntent();

    name = (TextView) findViewById(R.id.name);
    deal = (TextView) findViewById(R.id.deal);
    valid = (TextView) findViewById(R.id.valid);
    address = (TextView)findViewById(R.id.address);
    String message = intent.getExtras().getString("message");

    try {
        json = new JSONObject(message);
        String stime = json.getString("name");
        name.setText(stime);

        String slecturename = json.getString("deal");
        deal.setText(slecturename);

        String sroom = json.getString("valid");
        valid.setText(sroom);

        String sfaculty = json.getString("address");
        address.setText(sfaculty);


    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    serv=new GcmIntentService();
    //serv.CancelNotification(getApplicationContext());

}
}

Using above code I am able to receive notification, the problem is that if my activity is not in running condition and I receive the notification. At this time if I open the activity from notification the it shows fresh data but if activity is running and if at the same time notification arrives. If I open this notification then it is loading activity with old data. I want to display fresh data in activity even if I have activity running.

like image 781
Durga Avatar asked Mar 05 '14 10:03

Durga


1 Answers

When you get a new intent and either your activity is using singleTop or Intent is using FLAG_ACTIVITY_SINGLE_TOP, your new intents actually get delivered to the Activity's onNewIntent. Quoting the documentation:

This is called for activities that set launchMode to "singleTop" in their package, or if a client used the FLAG_ACTIVITY_SINGLE_TOP flag when calling startActivity(Intent). In either case, when the activity is re-launched while at the top of the activity stack instead of a new instance of the activity being started, onNewIntent() will be called on the existing instance with the Intent that was used to re-launch it.

An activity will always be paused before receiving a new intent, so you can count on onResume() being called after this method.

Note that getIntent() still returns the original Intent. You can use setIntent(Intent) to update it to this new Intent.

So your problem should be solved if you override that method in NotificationReceiveActivity.

like image 139
Menno Avatar answered Sep 23 '22 05:09

Menno