【问题标题】:Change android notification text dynamically动态更改android通知文本
【发布时间】:2014-11-07 10:28:33
【问题描述】:

我正在尝试为带有控件的音乐播放器发出通知。我成功收听了按钮单击事件,并且功能正在正确触发。我面临的唯一问题是更改这些点击事件的通知文本。 这就是我正在尝试的。

这是接收者成功接收呼叫并完美触发每一行。但我不能改变文字。我想我必须将内容视图重置为通知。如果是这样,我该怎么做?

@Override
public void onReceive(Context context, Intent intent) {
   String action = intent.getAction();
    if (action.equals("stop")) {
        ABCFragment.stopSong();
        Log.d("Notification","Stopping");
    }else if (action.equals("play")) {
        ABCFragment.togglePlayPause();
        Log.d("Notification","Toggle Play/Pause");
        RemoteViews contentView = new RemoteViews(context.getPackageName(),R.layout.notification_layout);
        contentView.setTextViewText(R.id.songName, "SOME NEW SONG");
    }else if (action.equals("next")) {
        ABCFragment.playNextSong();
        Log.d("Notification","Next");
    }
}

解决方案:

我更新了我的 Notification 类构造函数以传递一个额外的参数并让它工作!

@Override
public void onReceive(Context context, Intent intent) {
   String action = intent.getAction();
    if (action.equals("stop")) {
        ABCFragment.stopSong();
        Log.d("Notification","Stopping");
    }else if (action.equals("play")) {
        ABCFragment.togglePlayPause();
        Log.d("Notification","Toggle Play/Pause");
        new ABCNotification(context, "SOME NEW SONG");
    }else if (action.equals("next")) {
        ABCFragment.playNextSong();
        Log.d("Notification","Next");
    }
}

构造函数正在处理新传递的参数。

【问题讨论】:

    标签: android android-notifications android-remoteview


    【解决方案1】:

    您无法真正更改通知内容。这确实有点烦人,您只需将当前通知替换为带有新文本的新通知。

    我的应用有一个上传过程,我们每 3 秒更新一次通知以更改百分比。

    所以只需重新构建通知并使用相同的 ID 在NotificationManager 上调用notify()

    【讨论】:

    • 哦,现在所有文档都有意义了。感谢您指出。我试过了,它工作正常。我用解决方案更新了我的问题。
    • 另外请记住,如果您希望它更新漂亮而不是删除它并重新创建(这将使您的通知被删除并重新弹出列表中的其他位置),您需要使用builder.setOnlyAlertOnce(true) 以及你必须使用相同的构建器,否则它不会更新,它会做愚蠢的娱乐事情。 (我已经为此奋斗了好几天,但我似乎仍然无法让它更新按钮,它只会在现有按钮之外添加它们:-()
    猜你喜欢
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    相关资源
    最近更新 更多