I am working on Notifications and I have to use setLatestEventInfo. However, Android Studio shows the following error message:
cannot re
You write you have to use setLatestEventInfo. Does it mean you are ready to have your app not compatible with more recent Android versions? I strongly suggest you to use the support library v4 that contains the NotificationCompat class for app using API 4 and over.
If you really do not want to use the support library (even with Proguard optimization, using NotificationCompat will add a good 100Ko on the final app), an other way is to use reflection. If you deploy your app on an Android version that still has the deprecated setLatestEventInfo, first of all you should check if you are in such an environment, and then you use reflection to access the method.
This way, Android Studio or the compiler will not complain, since the method is accessed at runtime, and not at compile time. For instance :
Notification notification = null;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
notification = new Notification();
notification.icon = R.mipmap.ic_launcher;
try {
Method deprecatedMethod = notification.getClass().getMethod("setLatestEventInfo", Context.class, CharSequence.class, CharSequence.class, PendingIntent.class);
deprecatedMethod.invoke(notification, context, contentTitle, null, pendingIntent);
} catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
Log.w(TAG, "Method not found", e);
}
} else {
// Use new API
Notification.Builder builder = new Notification.Builder(context)
.setContentIntent(pendingIntent)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(contentTitle);
notification = builder.build();
}