使用NotificationCompat

使用NotificationCompat

简短问题:
我正试图使用NotificationCompat.Builder类来创建将用于服务的通知,但由于某些原因,我要么看不到该通知,要么在应销毁服务(或停止在前台)时无法取消该通知。
我的代码:

@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
    final String action = intent == null ? null : intent.getAction();
    Log.d("APP", "service action:" + action);
    if (ACTION_ENABLE_STICKING.equals(action)) {
        final NotificationCompat.Builder builder = new Builder(this);
        builder.setSmallIcon(R.drawable.ic_launcher);
        builder.setContentTitle("content title");
        builder.setTicker("ticker");
        builder.setContentText("content text");
        final Intent notificationIntent = new Intent(this, FakeActivity.class);
        final PendingIntent pi = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        builder.setContentIntent(pi);
        final Notification notification = builder.build();
        // notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
        // notification.flags |= Notification.FLAG_NO_CLEAR;
        // notification.flags |= Notification.FLAG_ONGOING_EVENT;

        startForeground(NOTIFICATION_ID, notification);
        // mNotificationManager.notify(NOTIFICATION_ID, notification);

    } else if (ACTION_DISABLE_STICKING.equals(action)) {
        stopForeground(true);
        stopSelf();
        // mNotificationManager.cancel(NOTIFICATION_ID);
    }
    return super.onStartCommand(intent, flags, startId);
}

评论的命令是我的试验,使之发挥作用。没有人因为某种原因而工作。
我甚至添加了一个假的活动,因为它想要一个内容意图,但它仍然不起作用。
有人能帮忙吗?

最佳答案

我刚才也遇到了同样的问题,我发现由于某种原因,通知id 0不能很好地与startForeground()一起工作,这是代码中NOTIFICATION_ID的值吗?
编辑:文档现在已更新为0是无效的ID

08-18 17:59