java - 如何发送每日通知但只发送一周?
问题描述
我的应用程序的一项功能是在特定时间发送每日通知。它工作正常,但我希望只发送这些通知一周并在此之后完成它。
我想让它像这样:用户单击按钮,它会激活一周内每天发送通知。是否有可能计算天数或可能执行了多少次功能?我不知道怎么做。。
这是我的代码:
创建频道:
public class App extends Application {
public static final String CHANNEL_1_ID = "channel1";
@Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
private void createNotificationChannel(){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel channel = new NotificationChannel( CHANNEL_1_ID, "channel 1", NotificationManager.IMPORTANCE_HIGH);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
}
}
通知 :
public class WeekChallengeBroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
MyDBHandler myDBHandler = new MyDBHandler(context, null,null,3);
ChallengesManager challengesManager = new ChallengesManager(context);
int id;
id = challengesManager.GetID();
NotificationCompat.Builder notification = new NotificationCompat.Builder(context, CHANNEL_1_ID )
.setSmallIcon(R.drawable.ic_stat_name)
.setContentTitle( myDBHandler.loadChallengeNotificationRow1(id))
.setContentText(myDBHandler.loadChallengeNotificationRow2(id))
.setStyle(new NotificationCompat.BigTextStyle())
.setPriority(Notification.PRIORITY_MAX)
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setAutoCancel(false)
.setVibrate(new long[]{1000});
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(2, notification.build());
}
}
激活通知的功能:
void ActivateNotifications(){
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 16);
calendar.set(Calendar.MINUTE, 45);
calendar.set(Calendar.SECOND, 0);
if (calendar.getTime().compareTo((new Date())) < 0)
{
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
Intent intent = new Intent(mContext.getApplicationContext(), WeekChallengeBroadcast.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext.getApplicationContext(), 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
if(alarmManager != null){
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,pendingIntent);
}
}
解决方案
推荐阅读
- r - 如何从 tibble 单元格中提取可变数元素列表?
- angular - 可以在实时 Web 应用程序上以开发人员模式运行 Angular 吗?
- terraform - Classic Load Balancer 不接受来自 ACM 的证书
- python-3.x - 根据许多条件过滤 Pandas 数据框
- android - 如何使用 Android API 为 WebRTC 设置硬件编码器
- c# - 在异步应用程序中修改了集合?
- c# - 正确显示天数字符串数组中的天数
- javascript - 如何使用浏览器下载管理器从 express + mongoDB 服务器下载/流式传输文件
- php - 是否可以在 Windows 中启用 PHP 5 的 VT100/ANSI 转义码
- excel - 用于隐藏所有数据透视表值的动态 VBA 宏