java - Android通知信息不在java类ArrayList中
问题描述
我正在创建一个应用程序,它在指定时间段内“捕获”所有通知,然后一次显示它们。但是,我的 NotificationListenerService Java 类遇到了问题。
我目前能够“捕捉”它们通过并阻止它们显示的通知。我还能够在 ArrayLists 中保存通知信息(如您在 onNotificationPosted 方法中所见)。但是,当我尝试使用其中一个 ArrayList getter 将信息拉入另一个类时,ArrayList 完全为空。关于为什么会这样以及为什么我不能在另一个 Java 类中提取这些信息的任何想法?
NotificationListenerService 类
public class NotificationListenerServiceUsage extends NotificationListenerService {
private static final String TAG = "NotificationListenerSer";
ArrayList<Integer> idMap = new ArrayList<>();
ArrayList<Notification> notificationMap = new ArrayList<>();
@Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "onBind: ");
return super.onBind(intent);
}
@Override
public void onNotificationPosted(StatusBarNotification sbn){
Integer notificationInt = sbn.getId();
Notification notificationContent = sbn.getNotification();
idMap.add(notificationInt);
notificationMap.add(notificationContent);
cancelAllNotifications();
}
@Override
public void onNotificationRemoved(StatusBarNotification sbn){
}
public ArrayList<Integer> getIdMap() {
return idMap;
}
public ArrayList<Notification> getNotificationMap() {
return notificationMap;
}
}
实现类
public class Batch_Notifications extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
public void getHeldNotifications(View view){
NotificationListenerServiceUsage noteListenerService = new NotificationListenerServiceUsage();
ArrayList<Integer> idMap = noteListenerService.getIdMap();
ArrayList<Notification> notificationMap = noteListenerService.getNotificationMap();
Log.d(TAG, "getHeldNotifications: " + idMap + notificationMap);
}
}
解决方案
您不能将数据持久保存在运行时内存中。您NotificationListenerService
将不会一直运行它会破坏然后再次实例化,现在您的所有属性都将重新初始化。
完成此类任务的最佳方法是将数据保存在持久存储(即数据库)中。当您尝试发送批处理通知时,您会从数据库中获得。您可以将 Sqlite 数据库与 Android-Room 一起使用,以便于植入。
推荐阅读
- react-native - 无法将没有 YogaNode 的子节点添加到没有度量函数的父节点
- algorithm - 不确定如何分解此分配任务
- ruby - return 语句中的空值表达式错误
- classification - Weka:不兼容的训练和测试集
- javascript - 在 javascript 横幅中使用 css 模糊图像
- java - Maven 和 Hibernate JPA 项目错误
- qt - 使用 cygwin 在 Nucleus 中构建 QT 应用程序
- math - 阅读下面的解释,因为我不知道如何构建这个
- wpf - 如何将检查事件传递给wpf mvvm中的按钮单击
- ios - 制作实例时如何为变量设置一个数字?