【发布时间】:2019-07-30 09:18:54
【问题描述】:
我有一个小应用程序,带有一个用于激活定期通知(工作经理定期工作请求)的按钮,它每 15 分钟发送一次测试通知
事情是当我按下按钮时,通知会立即发送,但只发送一次。即使我等待 20,30 分钟或将时间设置为 +1 小时,仅此而已
主活动:
private void initNotification() {
sendNotifButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
enableNotification();
}
})
private void enableNotification(){
NotificationWorker.scheduleReminder();
}
通知工作者:
private SharedPreferences preferences;
private String notifMessage = "Notification numéro : ";
private int notifNumber = 1;
public static final int notif_id = 1;
public NotificationWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@NonNull
@Override
public Result doWork() {
preferences = getApplicationContext().getSharedPreferences("key", Context.MODE_PRIVATE);
preferences.edit().putString("message", notifMessage).apply();
preferences.edit().putInt("numero", notifNumber + 1).apply();
sendNotification();
return Result.success();
}
private void sendNotification() {
String message = preferences.getString("message", null) + "" + preferences.getInt("numero", 50);
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("title")
.setContentText(message);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
builder.setContentIntent(pendingIntent);
NotificationManager manager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(notif_id, builder.build());
}
public static void cancelReminder() {
WorkManager instance = WorkManager.getInstance();
instance.cancelAllWorkByTag("worker_tag");
}
public static void scheduleReminder() {
PeriodicWorkRequest.Builder notificationWork = new PeriodicWorkRequest.Builder(NotificationWorker.class,
15, TimeUnit.MINUTES)
//Set network connected required to periodicWorkRequest
.setConstraints(new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED).build());
PeriodicWorkRequest request = notificationWork.build();
WorkManager.getInstance().enqueueUniquePeriodicWork("worker_tag", ExistingPeriodicWorkPolicy.REPLACE , request);
}
}
此功能必须在更大的项目中实现,但我无法每 15 分钟发送一次通知
【问题讨论】:
-
您能分享一下您的日志中发生了什么吗?
标签: java android notifications android-workmanager periodic-task