如何使用NotificationCompat.Builder和startForeground?

11

简短问题:

我正在尝试使用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);
}

这些被注释的命令是我尝试让它工作的。由于某些原因,都没有成功。

我甚至添加了一个虚假的活动,因为它需要一个contentIntent,但它仍然不起作用。

请问有人能帮忙吗?


这篇帖子连同被采纳的答案,在我苦苦思索多日后,终于解决了我的问题。 - midiwriter
1个回答

9

我之前也遇到过同样的问题,后来发现由于某种原因,通知ID为0与startForeground()不兼容。请问你的代码中NOTIFICATION_ID的值是多少?


编辑:文档已更新,将0标记为无效ID。


是的。没想过改变它,因为我通常从这个数字开始做任何事情...你确定它会修复它吗? - android developer
我在那里找到了答案(https://dev59.com/VWoy5IYBdhLWcg3wKrCs),显然这是众所周知的。它也为我和那篇帖子的OP解决了问题,所以它应该也能解决你的问题。最好的方法是尝试一下 :) - Joffrey
最终,您会成功的!如果您确认问题已解决,请接受答案 :) 我希望他们能尽快修复它,因为对于第一次使用“startForeground”的任何人来说,这真的很烦人,我们几乎都使用0作为ID,并花费数小时寻找问题的源头... - Joffrey
记录一下,这不是一个bug;文档清楚地说明了这个值不应该为0:https://developer.android.com/reference/android/app/Service.html - personne3000
@personne3000 是的,现在已经是2014年了,文档终于更新了!以前关于无效ID的内容几乎没有,所以我在1.5年前就说他们应该更新文档。 - Joffrey
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接