ntm ntm - 4 months ago 15
Java Question

make notification clickable and undestroyable

i tried to create a notification that starts a activity by clicking on it and wich you cant swipe away.

NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher))
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("DroidSchool")
.setContentText("DroidSchool l\u00E4uft im Hintergrund...");

Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, Intent.FLAG_FROM_BACKGROUND);

NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

int mId = 1234567890;
mNotificationManager.notify(mId, mBuilder.build());


with the code above the notification gets displayed but nothing happens when i click on it and you can swipe it away.

Answer

To keep the Notification, in that way the user can't click it away in any way, add this flag

Notification mNotification = mBuilder.build();
notification.flags = Notification.FLAG_NO_CLEAR;
mNotificationManager.notify(mId, notification);

To start an Activity you have to use this flag for your Intent

Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
Comments