首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >安卓系统中的notificationManager.notify和startForeground有什么不同?

安卓系统中的notificationManager.notify和startForeground有什么不同?
EN

Stack Overflow用户
提问于 2019-12-22 22:23:16
回答 1查看 786关注 0票数 4

我很好奇安卓系统中的NotificationManager.notifystartForeground有什么不同。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-22 23:46:37

使用NotificationManager.notify,您可以发布任意多的通知更新,包括通过Noticiation.Builder.setProgress对进度条进行调整,这样您就只向用户显示一个通知,这就是startForeground所要求的通知。

当您想要通过startForeground()更新通知集时,只需构建一个新的通知,然后使用NotificationManager来通知它。

关键点是使用相同的通知id。

我没有测试重复调用startForeground()来更新通知的场景,但我认为使用NotificationManager.notify会更好。

更新通知不会将服务从前台状态移除(这只能通过调用stopForground来完成。

下面是一个示例:

代码语言:javascript
运行
复制
private static final int notif_id=1;

@Override
public void onCreate (){
    this.startForeground();
}

private void startForeground() {
    startForeground(notif_id, getMyActivityNotification(""));
}

private Notification getMyActivityNotification(String text){
    // The PendingIntent to launch our activity if the user selects
    // this notification
    CharSequence title = getText(R.string.title_activity);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MyActivity.class), 0);

    return new Notification.Builder(this)
            .setContentTitle(title)
            .setContentText(text)
            .setSmallIcon(R.drawable.ic_launcher_b3)
            .setContentIntent(contentIntent).getNotification();     
}

/**
 * this is the method that can be called to update the Notification
 */
private void updateNotification() {
    String text = "Some text that will update the notification";

    Notification notification = getMyActivityNotification(text);

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(notif_id, notification);
}

您可以找到有关NotificationManager.notify here的更多示例和说明

为了了解更多关于startForeground的知识,我还建议您参考这个page

可以在here中找到startForeground的用法

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59445044

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档