首页 > 解决方案 > 收到通知时如何更改 textView 值?

问题描述

我正在尝试制作一个程序,当手机上出现通知时会更改 TextView 的值。

在我的 MainActivity 我有一个方法:

private void changeText(){
    TextView textNotificationView = (TextView) findViewById(R.id.textNotificationView);
    textNotificationView.setText(R.string.textGotNotification);
}

changeText()每当我收到通知时,我都想从 MainActivity打电话。为此,我创建了一个名为 NotificationListener 的类,它扩展了 NotificationListenerService。

public class NotificationListener extends NotificationListenerService {


@Override
public IBinder onBind(Intent intent) {
    return super.onBind(intent);
}

@Override
public void onNotificationPosted(StatusBarNotification sbn) {
    //Change value of TextView
}

@Override
public void onNotificationRemoved(StatusBarNotification sbn){

}
}

基本上,我想在 -method 中调用changeText()-method onNotificationPosted(StatusBarNotification sbn)

我该怎么做?

标签: androidandroid-notifications

解决方案


我有一个解决方案,即使用 EventBus

首先,创建一个事件

public class NotificationPosted {
// empty if you don't need to pass data
}

二、注册这个事件在MainActivity

@Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }


@Override
protected void onStop() {
    EventBus.getDefault().unregister(this);
    super.onStop();
}




  @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
        public void onEvent(NotificationPosted notificationPosted) {
            changeText()
        }

最后,将您的活动发布到NotificationListener

public void onNotificationPosted(StatusBarNotification sbn) {
    EventBus.getDefault().post(new NotificationPosted());
}

推荐阅读