如何使用NotificationCompat.Builder和startForeground? [英] How to use NotificationCompat.Builder and startForeground?
问题描述
短的问题:
我试图用NotificationCompat.Builder类,以创建将用于服务的通知,但由于某些原因,我不是没有看到通知,或者当无法取消服务应该被销毁(或从前景被停止)。
I'm trying to use the NotificationCompat.Builder class in order to create a notification that will be used for the service, but for some reason, i either don't see the notification, or can't cancel it when the service should be destroyed (or stopping from being in the foreground) .
我的code:
@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);
}
注释的命令是我的考验,使其工作。没有工作的某些原因。
The commented commands are my trials to make it work. none worked for some reason.
我甚至增加了一个假的活动,因为它需要一个contentIntent,但它仍然无法正常工作。
I even added a fake activity since it wanted a contentIntent , but it still doesn't work.
任何人都可以请帮助?
推荐答案
我前一阵子有完全相同的问题,我发现,由于某些原因,通知ID 0不能很好地<$ C $工作C> startForeground(),它是 NOTIFICATION_ID
?
I had the exact same problem a while ago, and I found out that for some reason, the notification ID 0 doesn't work well with startForeground()
, is it the value of NOTIFICATION_ID
in your code?
编辑:文档现在已经更新声明,0是无效ID
the documentation has now been updated to state that 0 is an invalid ID
这篇关于如何使用NotificationCompat.Builder和startForeground?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!