6

I'm sending extra string with pending intent from my StateCh.java to MainActivity. My expectation on it is to display dialog in MainActivity when pending intent with extra is arrived (notification is clicked). The problem is when i open the MainActivity and then I click the notification there is no extras inside pending intent and dialog isn't displayed. When I pause the MainActivity (by pressing back button) and click the notification again it works as expected.

MainActivity.java:

public class MainActivity extends Activity {

 //...

  @Override
protected void onNewIntent(Intent intent)   {
    super.onNewIntent(intent);

    Bundle extras = getIntent().getExtras();
    if(extras !=null) {
        String value1 = extras.getString("message");
        Log.v("alert", value1);

        AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
        alertDialog.setTitle("title");
        alertDialog.setMessage(value1);
        alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {

                //startActivity(MainActivity.this.getIntent());

            }
        });

        alertDialog.show();
    }
 }
}

StateCh.java:

public class StateCh extends Service {

//...

   private void notificationU(String title, String text)  {

    //The intent to launch when the user clicks the expanded notification
    Intent intent = new Intent(this, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    intent.putExtra("message", "something");
    intent.setAction("actionstring" + System.currentTimeMillis());

    PendingIntent pendIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

     Notification noti2 = new NotificationCompat.Builder(this)
     .setContentTitle(title)
     .setContentText(text)
     .setSmallIcon(R.drawable.warning)
     .setContentIntent(pendIntent)
     .build();

     mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
     mNotificationManager.notify(123456, noti2);
    }

    // ...      

}
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
XorOrNor
  • 8,868
  • 12
  • 48
  • 81

1 Answers1

8

Change Bundle extras = getIntent().getExtras();

To Bundle extras = intent.getExtras();

or call setIntent(intent) first

FunkTheMonk
  • 10,908
  • 1
  • 31
  • 37