Работа диспетчера и создание уведомлений Android - PullRequest
0 голосов
/ 03 мая 2020

Я создаю приложение для уведомлений, в котором оно хранит уведомления, и они выталкивают их сразу за определенный промежуток времени. Я расширил службу прослушивания уведомлений, чтобы блокировать уведомления, когда они приходят, и сохранять их в БД для будущего использования (см. Этот код ниже, но я не думаю, что моя проблема заключается здесь - NotificationListenerServiceUsage. java). Я использую WorkManager для тайм-аута периодических c выпусков уведомлений.

Когда WorkManager запускается, я проверяю, что уведомление не блокируется службой прослушивания, создаю уведомление и уведомляю, тогда последний вызываемый мною метод - это метод для повторной блокировки всех будущих уведомлений. ,

Проблема

Проблема, с которой я сталкиваюсь, заключается в том, что уведомления фактически не отправляются до тех пор, пока ПОСЛЕ WorkManager не завершит работу. И к этому моменту я уже блокирую уведомления. Так есть ли в действительности фактически pu sh уведомления DURING задача WorkManager?

NotificationListenerServiceUsage. java

public class NotificationListenerServiceUsage extends NotificationListenerService {
    private static final String TAG = "NotificationListenerSer";


    @Override
    public IBinder onBind(Intent intent) {
        return super.onBind(intent);
    }

    @Override
    public void onNotificationPosted(StatusBarNotification sbn){

        // 1. Getting DB Context and initializing SQLiteDatabase
        Context context = getApplicationContext();
        SQLiteDatabase sqLiteDatabase = context.openOrCreateDatabase("notifications", Context.MODE_PRIVATE,null);


        // 2. Initialize the DBHelper class and the Notification Object
        DBHelper dbHelper = new DBHelper(sqLiteDatabase);
        boolean pushNotificationValue = dbHelper.readNotificationReleaseStatus();

        // 3. IF the release status if false, holds and stores the notification
        if(pushNotificationValue == false) {
            cancelAllNotifications();
        }

        // Else just publish notification
    }

    @Override
    public void onNotificationRemoved(StatusBarNotification sbn){
        // 1. Getting DB Context and initializing SQLiteDatabase
        Context context = getApplicationContext();
        SQLiteDatabase sqLiteDatabase = context.openOrCreateDatabase("notifications", Context.MODE_PRIVATE,null);

        // 2. Initialize the DBHelper class and the Notification Object
        DBHelper dbHelper = new DBHelper(sqLiteDatabase);
        NotificationObject notificationObject = new NotificationObject();

        // 3. Getting the content for the DB and storing it in a Notification Object
        // for Serialization
        notificationObject.setNotificationKey(sbn.getKey());
        notificationObject.setNotificationID(sbn.getId());
        notificationObject.setPostTime(sbn.getPostTime());
        notificationObject.setNotificationPackage(sbn.getPackageName());
        notificationObject.setNotificationTitle(sbn.getNotification().extras.getString("android.title"));
        notificationObject.setNotificationBody(sbn.getNotification().extras.getString("android.text"));

        // 3.1 Converting the Notification Object into a String
        Gson gson = new Gson();
        String notificationInput = gson.toJson(notificationObject);

        // 4. Saving into the DB
        dbHelper.saveNotifications(notificationInput);
    }
}

* NotificationWorker. java

public class NotificationWorker extends Worker {

    private static final String TAG = "NotificationWorker";
    public static final String CHANNEL_1_ID = "channel1";
    Context context;
    WorkerParameters params;

    // Default constructor
    public NotificationWorker(@NonNull Context context, @NonNull WorkerParameters params) {
            super(context, params);
            this.context = context;
            this.params = params;
    }

    @NonNull
    @Override
    public Result doWork() {
        Log.d(TAG, "doWork: ");

        turnTrue();

        createNotificationChannel();
        getHeldNotifications();

        turnFalse();

        // Indicate whether the task finished successfully with the Result
        return Result.success();
    }

    // Ensures that the notifications ARENT blocked
    private void turnTrue(){
        Context context = getApplicationContext();
        SQLiteDatabase sqLiteDatabase = context.openOrCreateDatabase("notifications", Context.MODE_PRIVATE,null);

        // 2. Initialize the DBHelper class.
        DBHelper dbHelper = new DBHelper(sqLiteDatabase);
        dbHelper.setTrueNotificaitonReleaseUpdate();
    }

    // Ensures that all the notifications ARE blocked
    private void turnFalse(){
        Context context = getApplicationContext();
        SQLiteDatabase sqLiteDatabase = context.openOrCreateDatabase("notifications", Context.MODE_PRIVATE,null);

        // 2. Initialize the DBHelper class.
        DBHelper dbHelper = new DBHelper(sqLiteDatabase);
        dbHelper.setFalseNotificaitonReleaseUpdate();
    }


    private void getHeldNotifications(){
        Log.d(TAG, "getHeldNotifications: ");
        ArrayList<NotificationObject> notificationObjects;

        // 1. Getting DB Context and initializing SQLiteDatabase
        Context context = getApplicationContext();
        SQLiteDatabase sqLiteDatabase = context.openOrCreateDatabase("notifications", Context.MODE_PRIVATE,null);
        SQLiteDatabase sqLiteDatabase1 = context.openOrCreateDatabase("notifications", Context.MODE_PRIVATE,null);


        // 2. Initialize the DBHelper class.
        DBHelper dbHelper = new DBHelper(sqLiteDatabase);
        DBHelper dbHelper1 = new DBHelper(sqLiteDatabase1);


        // 3. Getting the notifications from the DB as a NotificationObject
        notificationObjects = dbHelper.readNotifications();
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(getApplicationContext());
        int i = 0;

        for (NotificationObject object: notificationObjects) {
            i += 1;
            NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_1_ID)
                    .setSmallIcon(R.drawable.ic_launcher_background)
                    .setContentTitle(object.getNotificationTitle())
                    .setContentText(object.getNotificationBody())
                    .setPriority(NotificationCompat.PRIORITY_HIGH);
            notificationManager.notify(i, builder.build());
        }
        Log.d(TAG, "getHeldNotifications: " + dbHelper1.readNotificationReleaseStatus());
    }

    private void createNotificationChannel() {
        Log.d(TAG, "createNotificationChannel: ");
        // Create the NotificationChannel, but only on API 26+ because
        // the NotificationChannel class is new and not in the support library
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "Custom Notification Channel";
            String description = "Description";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(CHANNEL_1_ID, name, importance);
            channel.setDescription(description);

            // Register the channel with the system; you can't change the importance
            // or other notification behaviors after this
            NotificationManager notificationManager = this.context.getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }
}
...