Android:启动前台服务无法正确显示通知

15

我正在开发一个使用前台服务的应用程序。为此,我从服务的 onStartCommand 回调中调用 startForeground(id,Notification)

我使用通知构建器创建我的通知,但当我将其传递给 startForeground 时,只有 ticker 文本显示为我设定的内容,其他所有内容都变成了默认值,即标题显示为“ is running”,而我本来想设置为“ is online”。

使用 setText 和 setInfo 方法在 notification.Builder 中设置的任何内容都不会显示出来,而是显示类似“触摸以获取更多信息或停止应用程序”这样的默认文本。

以下是相关的代码:

服务:

private final int NOTIFICATION_ID=1;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this,"EDI: Core service Started" , Toast.LENGTH_LONG).show();
        startForeground(NOTIFICATION_ID, CoreServiceNotification.getNotification(this, "EDI is online", "Online","Online and running","EDI just started"));
        return super.onStartCommand(intent, flags, startId);
    }

核心服务通知:

public class CoreServiceNotification {

        public static Notification getNotification(Context context,String title,String text,String info,String tickerText){
            Notification.Builder notificationBuilder= new Notification.Builder(context);
            notificationBuilder.setContentTitle(title);
            notificationBuilder.setContentText(text);
            notificationBuilder.setContentInfo(info);
            notificationBuilder.setTicker(tickerText);
            notificationBuilder.setLights(0x00ffff00, 1000, 0);
            return notificationBuilder.build();
        }

    }

RESULT: 这里输入图片描述


我认为你忘记了创建 NotificationManager notificationManager; 对象,然后你需要添加像 notificationManager.notify("1",notificationBuilder); 这样的代码。 - M D
1
不,我正在将通知对象传递给服务的StartForeground方法,请在此处查看该方法链接 - Allahjane
那么你的问题是什么? - M D
请阅读问题!我设置的文本并不是实际通知中显示的内容。 - Allahjane
7
尝试在构建通知并调用startForeground()之前调用notificationBuilder.setSmallIcon(R.drawable.ic_launcher),这对我解决了问题。 - jeremija
显示剩余2条评论
1个回答

36

我认为在创建通知时先设置小图标是必要的。

Notification.Builder notificationBuilder= new Notification.Builder(context);
notificationBuilder.setSmallIcon(R.drawable.yourIcon);
// then set other staff...

这是来自Cousera Android课程的另一个简单示例, 点击这里


将smallIcon设置为第一个并不能避免异常! - Tano
不知道这是如何解决我的问题的。无论如何,非常感谢! - Yasin Kaçmaz
1
我发现在Android 8.1中不再需要先设置它,但是必须设置它 - 或者其他设置,比如Intents(!)会被忽略。 - nsandersen

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