Skip to content

Instantly share code, notes, and snippets.

@mooingcat
Last active March 7, 2019 01:18
Show Gist options
  • Save mooingcat/8ef7ea9957197b3cb5b3d444a4f19efd to your computer and use it in GitHub Desktop.
Save mooingcat/8ef7ea9957197b3cb5b3d444a4f19efd to your computer and use it in GitHub Desktop.
Testing with Robolectric what the intent is when clicking a notification in android
@Test
public void clickingOnTheTextOpensANotificationWhichOpensTheResultActivity() {
DeckardActivity activity = Robolectric.setupActivity(DeckardActivity.class);
View text = activity.findViewById(R.id.text);
text.performClick();
NotificationManager notificationService = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE);
ShadowNotificationManager shadowNotificationManager = shadowOf(notificationService);
assertThat(shadowNotificationManager.size(), equalTo(1));
Notification notification = shadowNotificationManager.getAllNotifications().get(0);
//This next line surprised me! I was gonna try notification.getLatestEventInfo().getContentIntent();
PendingIntent contentIntent = notification.contentIntent;
Intent nextIntent = shadowOf(contentIntent).getSavedIntent();
//Now we have the intent and can check things about it as usual, e.g. next class name, extras
String nextClassName = nextIntent.getComponent().getClassName();
assertThat(nextClassName, equalTo(ResultActivity.class.getName()));
}
//Somewhere in the activity, when a notification is triggered...
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(android.R.drawable.btn_star)
.setContentTitle("My notification")
.setContentText("Hello World!");
Intent resultIntent = new Intent(this, ResultActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ResultActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, builder.build());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment