如何在收到通知时更改 textView 值?

How to change textView value when getting a notification?

我正在尝试制作一个程序,当 phone 上出现通知时,TextView 的值会发生变化。

在我的 MainActivity 中有一个方法:

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

我想在收到通知时从 MainActivity 调用 changeText()。为此,我创建了一个名为 NotificationListener 的 class,它扩展了 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){

}
}

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

我应该怎么做?

您需要从非 activity class 回调到 Activity class。

public class MainActivity extends Activity implements INotificationCallback {  
    public void setText(String value) {
        TextView textNotificationView = (TextView) findViewById(R.id.textNotificationView);
        textNotificationView.setText(value);
    }  
}

public NotificationListener extends NotificationListenerService {
    public interface INotificationCallback {
        public void setText(String value);
    }   

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        activity.setText(value); 
    }  
} 

我有一个解决方案,那就是使用 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()
        }

最后,post 你的活动在 NotificationListener

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