You write < to use setLatestEventInfo . Does this mean that you are ready to ensure that your application is not compatible with later versions of Android? I highly recommend you use the v4 support library , which contains the NotificationCompat class for an application that uses API 4 or more.
If you really don't want to use the support library (even when optimizing Proguard, using NotificationCompat will add a good 100Ko in the final application), another way is to use reflection. If you are deploying your application in the Android version, which still has an outdated setLatestEventInfo , you must first check if you are in such an environment and then use reflection to access the method.
This way, Android Studio or the compiler will not complain, since the method is available at runtime, and not at compile time. For example:
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(); }
Vincent Hiribarren Oct. 12 '15 at 16:18 2015-10-12 16:18
source share