当前,如果我们的设备连接到WiFi,则WhatsApp将通过在通知区域显示进度栏来执行与云的同步。
我想知道,如何使用WorkManager
做到这一点?目前,我知道我可以为WorkManager
设置特定的约束以运行后台作业。
但是,我们如何通过WorkManager
显示通知UI?
答案 0 :(得分:0)
在我看来,这可以为您提供帮助。 这个想法是创建一个工作程序,并放置您的逻辑以获取进度并使用处理程序将更新显示为通知。
注意:这段代码未经测试,我只是在解释方式
工人代码
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.)
}}
还有另一个使用该处理程序的类将更新发送到通知
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);
}}