Cannot Resolve Method setLatestEventInfo

后端 未结 4 2353
夕颜
夕颜 2020-11-27 03:28

I am working on Notifications and I have to use setLatestEventInfo. However, Android Studio shows the following error message:

cannot re

4条回答
  •  佛祖请我去吃肉
    2020-11-27 04:17

    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();
    }
    

提交回复
热议问题