Android - 如何使用API​​在API< 11中显示通知

时间:2015-10-11 09:56:55

标签: android notifications

在API 23(Android 6.0 Marshmallow)之前,我们可以使用此代码显示通知

Notification myNotification8 = new Notification(R.drawable.android, "this is ticker text 8", System.currentTimeMillis());

            Intent intent2 = new Intent(MainActivity.this, SecondActivity.class);
            PendingIntent pendingIntent2 = PendingIntent.getActivity(getApplicationContext(), 2, intent2, 0);
            myNotification8.setLatestEventInfo(getApplicationContext(), "API level 8", "this is api 8 msg", pendingIntent2);
                NotificationManager manager = manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            manager.notify(11, myNotification8);

出现此错误:

  

无法解析方法setLatestEventInfo

根据这些answerdocumentation,删除了方法setLatestEventInfo。

所以问题 - 是否可以在API< 11中显示通知而不更改 compileSdkVersion 23

1 个答案:

答案 0 :(得分:0)

有两种可能性。最好的方法是使用包含NotificationCompat类的support library v4来使用API​​ 4及更高版本的app。但我想它不会回答你的问题。

另一种方法是使用反射。如果您在仍然不推荐使用setLatestEventInfo的Android版本上部署您的应用,请首先检查您是否处于此类环境中,然后使用反射来访问该方法。

这样,Android Studio或编译器就不会抱怨,因为该方法是在运行时访问,而不是在编译时访问。例如:

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