如何使用NotificationCompat.Builder和startForeground?

时间:2013-04-28 11:04:55

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

简短的问题:

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

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:9)

前一段时间我遇到了完全相同的问题,我发现由于某种原因,通知ID 0与startForeground()无效,是你NOTIFICATION_ID的价值码?


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

相关问题