8

简短问题:如何使用NotificationCompat.Builder和startForeground?

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

任何人都可以请帮忙吗?

+0

这个帖子,有公认的答案一起,几天努力寻找解决方案后,固定我的问题。 – 2016-06-20 00:14:23

回答

9

前段时间我有完全相同的问题,并且我发现由于某种原因,通知ID 0与startForeground()不兼容,请问您的代码中是否为NOTIFICATION_ID的值?


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

+0

是的。它是。没想到会改变它,因为我通常从这个数字开始,确定它会修复它? – 2013-04-28 19:00:28

+0

我已经找到答案[有](http://stackoverflow.com/questions/8725909/startforeground-does-not-show-my-notification),显然它是已知的。它为我修复了这个帖子的OP,所以它也应该修复你的问题。最好的方法是尝试:) – Joffrey 2013-04-28 22:59:38

+0

每当我对自己说,我无法找到任何在Android上的怪物错误... – 2013-04-28 23:09:53

相关问题