android - 收到通知时如何更改 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)
。
我该怎么做?
解决方案
我有一个解决方案,即使用 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());
}
推荐阅读
- kubernetes - 为每个虚拟主机应用 envoyfilter ext_authz
- java - 运行 `mvn endpoints-framework:openApiDocs` 时出现 ClassNotFoundException
- sql-server - 部署 SSIS 包需要 Windows 身份验证?
- ruby - 卢卡斯公式用递归求解。然而公式尚未定义
- matlab - 如何(倾斜)旋转 500 x 1000 矩阵?- MATLAB
- vim - vim - 如何选择和抽出所有评论?
- python - Discord.py 上的轮询系统
- angular - 无法使用默认 PipeDate
- vega - 如何在 *url* 参数上使用 vega 中的动态数据加载示例?
- javascript - 将单选按钮值获取到段落