所以我使用PeriodicRequest每15分钟向我发送一次通知,但它根本没有出现。一旦我终止了应用程序,强制关闭的选项就会被禁用。这不是意味着没有后台进程在运行吗?这就是我的通知没有出现的原因吗?
PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest.Builder((BackgroundWork.class),
15, TimeUnit.MINUTES).build();
WorkManager.getInstance(this).enqueue(periodicWorkRequest);
下面的代码来自BackgroundWork类。
public Result doWork() {
NotificationCompat.Builder alertNotify = new
NotificationCompat.Builder(context1,"101")
.setContentTitle("Test")
.setContentText("Test notif")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setSmallIcon(R.drawable.virus)
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.setAutoCancel(true); //removes notification when user clicks
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(context1);
notificationManager.notify(28,alertNotify.build());
DataParser download = new DataParser(context);
download.execute("https://api.covid19api.com/summary");
return Result.success();
最佳答案
您似乎尚未设置要尝试添加通知的通知 channel 。作为测试,您可以在 NotificationCompat.Builder
设置之前添加此代码吗?
//Kotlin
val notificationManager = NotificationManagerCompat.from(context)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationManager.createNotificationChannel(NotificationChannel("101", "Test", NotificationManager.IMPORTANCE_DEFAULT))
}
//Java
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context1);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationManager.createNotificationChannel(new NotificationChannel("101", "Test", NotificationManager.IMPORTANCE_DEFAULT));
}
通知必须分配给 Android 8.0(API 级别 26)中的 channel 。请参阅NotificationChannel文档找到here
这很可能是通知未显示在您的设备上的原因,但工作人员肯定仍在工作。您可以在调试输出和 Logcat 窗口中查看 Workers 所做操作的一些日志。我自己测试的一些示例如下:
//Debug log
I/WM-WorkerWrapper: Worker result SUCCESS for Work [ id=aa30d1f6-8683-43b8-bf6d-67e7b38a6d75, tags={ com.test.stackoverflowtest.BackgroundWork } ]
//Logcat
2020-06-20 15:02:23.743 4827-4899/com.test.stackoverflowtest I/WM-WorkerWrapper: Worker result SUCCESS for Work [ id=aa30d1f6-8683-43b8-bf6d-67e7b38a6d75, tags={ com.test.stackoverflowtest.BackgroundWork } ]
关于java - 定期请求不起作用。我尝试每 15 分钟发送一次通知,但不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62486510/