【问题标题】:How to use NotificationCompat.Builder and startForeground?如何使用 NotificationCompat.Builder 和 startForeground?
【发布时间】:2013-04-22 03:33:12
【问题描述】:

小问题:

我正在尝试使用 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 ,但它仍然不起作用。

有人可以帮忙吗?

【问题讨论】:

  • 这篇文章连同接受的答案一起解决了我在解决问题几天后解决的问题。

标签: android android-service compatibility android-notifications foreground


【解决方案1】:

前段时间我遇到了完全相同的问题,我发现由于某种原因,通知 ID 0 与startForeground() 无法正常工作,是您代码中NOTIFICATION_ID 的值吗?


编辑:文档现已更新,说明 0 是无效 ID

【讨论】:

  • 是的。它是。没想过要更改它,因为我通常都以这个数字开头...确定它会解决它吗?
  • 我找到了答案there,显然它是已知的。它为我以及该帖子的 OP 修复了它,因此它也应该解决您的问题。最好的方法是尝试:)
  • 最终你做到了!如果您可以确认您的问题已解决,请接受答案 :) 我希望他们能尽快解决它,因为对于第一次使用 startForeground 的任何人来说,这真的很烦人,我们几乎都使用 0 作为 ID 并花费数小时寻找对于我们问题的根源......
  • 对不起,我无意冒犯你。我现在已经测试过了,这是正确的。使用 ID 值 1 工作得很好。
  • 完全没有被冒犯,只是说 Android 开发人员应该更正它(文档或框架)^^ 我很高兴它现在对你有用!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-22
  • 1970-01-01
  • 2017-05-15
  • 2018-12-16
相关资源
最近更新 更多