NotificationCompat Builder错误

时间:2016-09-24 20:06:54

标签: android

我在为媒体播放器制作通知时遇到问题。基本上我正在尝试使用“通知”构建器为我的媒体播放器构建远程控件。我使用NotificationCompat库来支持较低版本的android。下面是代码中面临错误的部分:

private NotificationCompat.Action createAction(int iconResId, String title, String action){
    Intent intent = new Intent(this, MusicBoxService.class);
    intent.setAction(action);
    PendingIntent pendingIntent = PendingIntent.getService(MainApplication.getContext(), 1, intent, 0);
    return new NotificationCompat.Action.Builder(iconResId, title, pendingIntent).build();
}

private void updateNotification(){
    NotificationCompat.Action playPauseAction = playbackState.getState() == playbackState.STATE_PLAYING ?
            createAction(R.drawable.ic_pause_black_18dp, "Pause", ACTION_PAUSE):
            createAction(R.drawable.ic_play_arrow_black_18dp, "Play", ACTION_PLAY);

    NotificationCompat notificationCompat = new NotificationCompat.Builder(this)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setCategory(NotificationCompat.CATEGORY_TRANSPORT)
            .setContentTitle(title)
            .setContentText(artist)
            .setOngoing(playbackState.getState() == playbackState.STATE_PLAYING)
            .setShowWhen(false)
            .setSmallIcon(R.drawable.ic_music_box_black_18dp)
            .setAutoCancel(false)
            .addAction(createAction(R.drawable.ic_skip_previous_black_18dp, "Previous", ACTION_PREV))
            .addAction(playPauseAction)
            .addAction(createAction(R.drawable.ic_skip_next_black_18dp, "Next", ACTION_NEXT))
            .setStyle(new NotificationCompat.MediaStyle().setMediaSession(mMediaSession.getSessionToken()).setShowActionsInCompactView(1,2))
                    .build();
    ((NotificationManagerCompat)getSystemService(Context.NOTIFICATION_SERVICE)).notify(1, notificationCompat);
}

以下是错误的屏幕截图: enter image description here

问题是将NotificationCompat notificationCompat = new ...更改为Notification notificationCompat = new ..解决了错误,但我不确定这是否正确。

Android Studio提供错误: 必需:android.support.v7.app.NotificationCompat 发现:android.app.Notification

谢谢! 非常感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

NotificationCompat仅用于构建Notification。使用NotificationCompat.Builder制作通知仍会返回android.app.Notification,而不是NotificationCompat。只需将notificationCompat的声明更改为:

Notification notification = new NotificationCompat.Builder(this)
        ...
        .build();