Pending intent extras are received only when activity is paused

时光总嘲笑我的痴心妄想 提交于 2019-12-10 13:19:19

问题


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);
    }

    // ...      

}

回答1:


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

To Bundle extras = intent.getExtras();

or call setIntent(intent) first



来源:https://stackoverflow.com/questions/16563265/pending-intent-extras-are-received-only-when-activity-is-paused

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!