为什么类型不兼容?

Why incompatible types?

我正在尝试在我的服务中使用 startForeground(int, id, notification),但为此我需要一个通知参数。在过去的 3 个小时里,我一直在尝试创建该通知,但它就是行不通:

 Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle("Notification title")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentText("Notification text");

错误如下:

我已经尝试删除和替换我所有的导入,但没有任何效果。我该如何解决这个问题?

谢谢,

鲁奇尔

您需要在通知生成器上调用 .build() 才能收到通知:

 Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle("Notification title")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentText("Notification text") // <---- NotificationCompat.Builder
                .build(); // <-------- 

您试图将 NotificationCompat.Builder 分配给 Notification

看这里:http://developer.android.com/reference/android/app/Notification.Builder.html

您会看到在链的末尾有一个最终的 .build() 。然后返回 Notification 对象。即尝试:

Notification notification = new NotificationCompat.Builder(this)
            .setContentTitle("Notification title")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentText("Notification text")
            .build();