Last active
March 7, 2019 01:18
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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())); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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