首页 > 解决方案 > 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);
    }
}


标签: javaandroidservicenotificationsandroid-notifications

解决方案


您不能将数据持久保存在运行时内存中。您NotificationListenerService将不会一直运行它会破坏然后再次实例化,现在您的所有属性都将重新初始化。

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

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


推荐阅读