Skip to content

Instantly share code, notes, and snippets.

@matthiaswenz
Last active September 1, 2015 14:46
Show Gist options
  • Save matthiaswenz/1fe0629c2ddddd8eb250 to your computer and use it in GitHub Desktop.
Save matthiaswenz/1fe0629c2ddddd8eb250 to your computer and use it in GitHub Desktop.
Android Notifications 2.3 - 6.0
public class NotificationUtil {
public static Notification createNotification(Context context, PendingIntent pendingIntent, String title, String text, int iconId) {
Notification notification;
if (isNotificationBuilderSupported()) {
notification = buildNotificationWithBuilder(context, pendingIntent, title, text, iconId);
} else {
notification = buildNotificationPreHoneycomb(context, pendingIntent, title, text, iconId);
}
return notification;
}
public static boolean isNotificationBuilderSupported() {
try {
return (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) && Class.forName("android.app.Notification.Builder") != null;
} catch (ClassNotFoundException e) {
return false;
}
}
@SuppressWarnings("deprecation")
private static Notification buildNotificationPreHoneycomb(Context context, PendingIntent pendingIntent, String title, String text, int iconId) {
Notification notification = new Notification(iconId, "", System.currentTimeMillis());
try {
// try to call "setLatestEventInfo" if available
Method m = notification.getClass().getMethod("setLatestEventInfo", Context.class, CharSequence.class, CharSequence.class, PendingIntent.class);
m.invoke(notification, context, title, text, pendingIntent);
} catch (Exception e) {
// do nothing
}
return notification;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressWarnings("deprecation")
private static Notification buildNotificationWithBuilder(Context context, PendingIntent pendingIntent, String title, String text, int iconId) {
android.app.Notification.Builder builder = new android.app.Notification.Builder(context)
.setContentTitle(title)
.setContentText(text)
.setContentIntent(pendingIntent)
.setSmallIcon(iconId);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
return builder.build();
} else {
return builder.getNotification();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment