【问题标题】:API Level specific code for Notifications gives errors for min required api level通知的 API 级别特定代码给出了所需的最低 API 级别的错误
【发布时间】:2014-07-16 18:19:22
【问题描述】:

我正在尝试让我的应用发出通知,但由于最低 api 级别为 11,我必须使用此代码:

 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
        // call something for API Level 16+
        Notification noti;

        noti = new Notification.Builder(this)
                .setContentTitle("New Notification from LCD")
                .setContentText("content")
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentIntent(pIntent)
                .addAction(R.drawable.ic_launcher, "Option1", pIntent)
                .addAction(R.drawable.ic_launcher, "Option2", pIntent)
                .addAction(R.drawable.ic_launcher, "Option3",
                        pIntent).build();
        NotificationManager nmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // hide notification
        noti.flags |= Notification.FLAG_AUTO_CANCEL;

        nmanager.notify(0, noti);
    }

我为 16 级以下的 API 级别设置了另一个,使用 .getNotification() 而不是 .build()。

即使在那之后我也收到了Call requires API level 16 (current min is 11) 错误。我该怎么做才能解决这个问题?

编辑:忘了添加,.getNotification 行给出了一个黄色错误,说The method getNotification() from the type Notification.Builder is deprecated

【问题讨论】:

    标签: android notifications


    【解决方案1】:

    您应该使用@SuppressLint("NewApi") 注释。 比如下面这个检测设备是否有物理菜单按钮的方法:

    @SuppressLint("NewApi")
    public static boolean hasMenuButton(Context ctx) {
        return (
            Build.VERSION.SDK_INT <= 10 || 
            (Build.VERSION.SDK_INT >= 14 && ViewConfiguration.get(ctx).hasPermanentMenuKey())
        );
    }
    

    编辑(进一步到 OP 的编辑): 同样,您可以使用 @SuppressWarnings("deprecation") 注释摆脱弃用警告。例如,下面的方法使用了一些 API11 下需要但之后弃用的代码。

    @SuppressWarnings("deprecation")
    private void initializeSurfaceHolder() {
        final SurfaceHolder holder = getHolder();
    
        holder.addCallback(this);
    
        if (Build.VERSION.SDK_INT < 11) {
            holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
    }  
    

    【讨论】:

    • 哇,谢谢,成功了!那么所做的只是阻止它检查该类型的错误?
    • 当然可以 :) 是的,完全正确。这是一种告诉编译器你知道你在做什么的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 2012-07-17
    • 1970-01-01
    相关资源
    最近更新 更多