• 13
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

Currently, if our device connected to WiFi, WhatsApp will perform sync to cloud, by showing a progress bar in notification area.

enter image description here

I was wondering, how can I achieve so using WorkManager? Currently, I know I can setup specific constraint, for WorkManager to run a background job.

  1. Delayed time
  2. Network constraint

But, how can we show a notification UI, via WorkManager?

    • This is an ongoing notification . NotificationCompat.Builder has method #setProgress which you can use .
      • 2
    • I don't think so . Well I do not have much experience with work manager so I can not make any specific comments on this .

Here is something which i have in my mind that can help. The idea is to create a worker and put your logic to get the progress and show updates as a notification using handler.

NOTE : This code is not tested and i am using it just to explain the way

Worker Code

public class CompressWorker extends Worker {

public CompressWorker(@NonNull Context context, @NonNull WorkerParameters params) {
    super(context, params);
}

@NonNull
@Override
public Result doWork() {
   ProgressManager manager = new ProgressManager();
   int i = 0;
   while(i<100){
       i++;
       try {
           Thread.sleep(1000);
           manager.updateProgress(i);
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
   }
    Log.i("Ansh", "worker's job is finished");
    // Indicate success or failure with your return value:
    return Result.success();

    // (Returning Result.retry() tells WorkManager to try this task again
    // later; Result.failure() says not to try again.)
}}

And there is another class using the handler to send the updates to the notification

public class ProgressManager {

Context context;
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);

Handler handler = new Handler(Looper.getMainLooper()) {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
                context);
        notificationBuilder.setProgress(100, msg.arg1, true);
        Notification notification = notificationBuilder.build();
        notificationManagerCompat.notify(1000, notification);
    }
};


public void updateProgress(int val) {
    Message msg = new Message();
    msg.arg1 = val;
    handler.sendMessageDelayed(msg, 1000);
}}
  • 1
Reply Report