Last active
September 1, 2015 14:46
-
-
Save matthiaswenz/1fe0629c2ddddd8eb250 to your computer and use it in GitHub Desktop.
Android Notifications 2.3 - 6.0
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
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