【问题标题】:Android - How to show notification in API<11 using APIAndroid - 如何使用 API 在 API<11 中显示通知
【发布时间】:2015-10-13 00:14:29
【问题描述】:

在 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方法。

所以问题 - 是否可以在 APIcompileSdkVersion 23?

【问题讨论】:

    标签: android notifications


    【解决方案1】:

    有两种可能性。最好的方法是使用包含 NotificationCompat 类的 support library v4 用于使用 API 4 及更高版本的应用程序。但我想它并没有回答你的问题。

    另一种方法是使用反射。如果您将应用部署在仍然具有已弃用 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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-05
      • 2019-08-21
      • 1970-01-01
      • 2019-01-31
      • 1970-01-01
      • 2022-12-19
      • 2022-11-17
      相关资源
      最近更新 更多