从通知中打开应用程序
假设我们有活动,它显示有趣的图片并将其命名为FunnyActivity。点击按钮后,此活动可从MainActivity启动,该活动是out应用程序中的基本Activity。我们还希望有时推送一些通知,当用户点击通知时,应该启动FunnyActivity。所以我们加入这部分代码:从通知中打开应用程序
Intent notificationIntent = new Intent(this, FunnyActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent intent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), notificationIntent, 0);
这的PendingIntent在通知建设者
setContentIntent(intent)
当然FunnyActivity是美丽的发射使用,但我们要打开MainActivity当用户单击后退按钮上FunnyActivity 。
我们该如何做到这一点?请记住,当用户回到MainActivity时,他可以再次从按钮打开FunnyActivity。
试试这个:
// Intent for the activity to open when user selects the notification
Intent detailsIntent = new Intent(this, DetailsActivity.class);
// Use TaskStackBuilder to build the back stack and get the PendingIntent
PendingIntent pendingIntent =
TaskStackBuilder.create(this)
// add all of DetailsActivity's parents to the stack,
// followed by DetailsActivity itself
.addNextIntentWithParentStack(upIntent)
.addNextIntent(detailsIntent);
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentIntent(pendingIntent);
看起来是正确的anwser!但是,在哪里使用detailsIntent? – ThirdMartian
@ThirdMartian之后.addNextIntentWithParentStack(upIntent) – shantanu
@ThirdMartian我更新了答案,'upIntent'是你想要打开的意向MainActivity。 – shantanu
你可以试试这个:
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
Intent resultIntent = new Intent(this, FunnyActivity.class);
// Adds the back stack
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent to the top of the stack
stackBuilder.addNextIntent(resultIntent);
Intent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)/*.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))*/
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(msg)
.setContentIntent(resultPendingIntent)
.setAutoCancel(true);
这是如何可以实现问题的解决方案。希望这可以帮助你
我不知道标准解决方案,这可能听起来像一个黑客,但你可以做的其中一件事是在FunnyActivity中重写'onBackPressed()',并在那里启动MainActivity。 – Shaishav