Android通知信息不在javaclassArrayList中

Android notification information not staying in java class ArrayList

我正在创建一个 "Catches" 指定时间段内的所有通知然后一次显示所有通知的应用程序。但是,我 运行 遇到了 NotificationListenerService Java class 的问题。

我目前能够 "Catch" 通知通过并阻止它们显示。我还能够在 ArrayLists 中保留通知信息(正如您在 onNotificationPosted 方法中看到的那样)。但是,当我尝试使用 ArrayList getter 之一将信息拉入另一个 class 时,ArrayList 完全是空的。关于为什么会这样以及为什么我不能在另一个 Java class?

中提取此信息的任何想法

NotificationListenerServiceClass

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;
    }
}

实施Class

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 不会总是 运行 它会破坏然后再次实例化,现在你的所有属性都将重新初始化。

完成此类任务的最佳方法是将数据保存在持久存储(即数据库)中。当您尝试发送从数据库中获取的批处理通知时。 Android-Room可以使用Sqlite数据库,方便植入。

看看https://developer.android.com/training/data-storage