首页 > 解决方案 > 如何发送每日通知但只发送一周?

问题描述

我的应用程序的一项功能是在特定时间发送每日通知。它工作正常,但我希望只发送这些通知一周并在此之后完成它。

我想让它像这样:用户单击按钮,它会激活一周内每天发送通知。是否有可能计算天数或可能执行了多少次功能?我不知道怎么做。。

这是我的代码:

创建频道:

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);
        }
    }

标签: javaandroidnotifications

解决方案


推荐阅读