Android:每日定时警报仅触发一次

我的应用需要触发每日通知,但出于任何奇怪的原因,它均无法正常运行,因为在大多数设备中,触发仅一次。我的应用程序允许将通知设置为每天一次,每天两次,每周一次,每周两次,每月一次,每月一次,每月两次或在设置中永远不会出现(我随机选择),因此我添加了评论,这样您就不会觉得我的代码太难理解了。

public static void scheduleNewThoughtAlarm(Context oContext) {
    if(!alarmNewThoughtAlreadySet(oContext)) {
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(oContext);
        //reminderPreference => notification interval
        int reminderPreference = Integer.valueOf(sharedPref.getString(Enum.Preference.NEWTHOUGHTREMINDER,"1"));
        //randomNotificationsPreference => user would like random notifications
        boolean randomNotificationsPreference = sharedPref.getBoolean(Enum.Preference.RANDOMNOTIFICATIONA,false);
        //reminderPreference==0 => notifications disabled.
        if (reminderPreference!=0){
            //This is firing correctly the first time app is run and not firing -also correctly- on subsequent runs.
            doNewThoughtSchedule(oContext,reminderPreference,randomNotificationsPreference);
        }else{
            cancelNewThoughtAlarm(oContext);
        }
    }
}

private static void doNewThoughtSchedule(Context oContext,int reminderPreference,boolean randomNotificationsPreference){

    Calendar reminderCal;

    //next two integers define a "time margin" where a person is usually awake
    int startHour = 8; //=> an hour of my choice that indicates when a person usually gets up
    int endHour = 23;  //=> an hour of my choice that indicates when a person usually goes to bed.
    int dayHours = endHour - startHour;
    int fractionsDivider = reminderPreference==1 || reminderPreference==3 || reminderPreference==5 ? 2 : 3;
    //I use next integer "fractions" to divide the "awake time margin" in equal fractions depending on
    //if notification is set to once per period or twice per period.
    int fractions = (int)Math.floor(dayHours / fractionsDivider);

    AlarmManager am = (AlarmManager) oContext.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(oContext,AlarmNewThoughtReceiver.class);

    int loops = reminderPreference==1 || reminderPreference==3 || reminderPreference==5 ? 1 : 2;
    for (int i=0; i<loops;i++){
        int notificationHour;
        int notificationminutes;
        if (randomNotificationsPreference){
            notificationHour = TMUtils.generateRandom(startHour,endHour);
            notificationminutes = TMUtils.generateRandom(0,59);
        }else{
            notificationHour = startHour + fractions*(i+1);
            notificationminutes = 00;
        }
        long interval = getInterval(reminderPreference);
        PendingIntent sender = PendingIntent.getBroadcast(oContext,i,intent,0);
        reminderCal = TMDate.generateHourCalendar(notificationHour,notificationminutes,0);

        am.setInexactRepeating(AlarmManager.RTC_WAKEUP,reminderCal.getTimeInmillis(),interval,sender);
    }
}

private static long getInterval(int reminderPreference) {

    /*<item>never</item>
    <item>once a day</item>
    <item>twice a day</item>
    <item>once a week</item>
    <item>twice a week</item>
    <item>once a month</item>
    <item>twice a month</item>*/

    long interval;
    switch(reminderPreference)
    {
        case 2:
            interval = AlarmManager.INTERVAL_DAY/2;
            break;
        case 3:
            interval = 7*AlarmManager.INTERVAL_DAY;
            break;
        case 4:
            interval = 7*AlarmManager.INTERVAL_DAY/2;
            break;
        case 5:
            interval = 30*AlarmManager.INTERVAL_DAY;
            break;
        case 6:
            interval = 30*AlarmManager.INTERVAL_DAY/2;
            break;
        default:
            interval = AlarmManager.INTERVAL_DAY;
            break;
    }

    return interval;
}

public static void cancelNewThoughtAlarm(Context oContext){

    Intent intent = new Intent(oContext,AlarmNewThoughtReceiver.class);
    PendingIntent sender = PendingIntent.getBroadcast(oContext,0);
    AlarmManager alarmManager = (AlarmManager) oContext.getSystemService(Context.ALARM_SERVICE);

    Objects.requireNonNull(alarmManager).cancel(sender);
}

private static boolean alarmNewThoughtAlreadySet(Context oContext) {

    return (PendingIntent.getBroadcast(oContext,new Intent(oContext,AlarmNewThoughtReceiver.class),PendingIntent.flaG_NO_CREATE) != null);
}

public static void Notify(String notificationTitle,String notificationmessage,int idNoti,Context oContext) {

    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(oContext,"notify_001");

    Intent ii = new Intent(oContext,DisplayThoughtactivity.class);
    ii.putExtra("source",Enum.activity.DISPLAYTHOUGHTactIVITY);

    PendingIntent pendingIntent = PendingIntent.getactivity(oContext,ii,PendingIntent.flaG_UPDATE_CURRENT);

    Bitmap bitmap = BitmapFactory.decodeResource(ApplicationContext.get().getResources(),R.drawable.artandwords_notification_large,null);

    mBuilder.setContentIntent(pendingIntent);
    mBuilder.setSmallIcon(R.drawable.artandwords_notification);
    mBuilder.setLargeIcon(bitmap);
    mBuilder.setContentTitle(notificationTitle);
    mBuilder.setContentText(notificationmessage);
    mBuilder.setPriority(Notification.PRIORITY_MAX);
    mBuilder.setautoCancel(true);
    mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(notificationmessage));

    Notificationmanager mNotificationmanager =
            (Notificationmanager) oContext.getSystemService(Context.NOTIFICATION_SERVICE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        String channelId = "notify_002";
        NotificationChannel channel = new NotificationChannel(channelId,notificationTitle,Notificationmanager.IMPORTANCE_DEFAULT);
        mNotificationmanager.createNotificationChannel(channel);
        mBuilder.setChannelId(channelId);
    }

    mNotificationmanager.notify(idNoti,mBuilder.build());
}

接收器:

public class AlarmNewThoughtReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context oContext,Intent intent) {

        try {
            String notificationmessage = TMLocale.getStringResourceByName("reminder_newthought");
            String notificationTitle = TMLocale.getStringResourceByName("app_name");

            TMNotification.Notify(notificationTitle,notificationmessage,oContext);
        } catch (Exception e) {
            ExceptionHandler.logException(e);
        }
    }
}

日期实用程序:

public static Calendar generateHourCalendar(int hour,int minutes,int seconds) {

    Calendar cal = Calendar.getInstance();
    cal.setTimeInmillis(System.currentTimeMillis());

    cal.set(Calendar.HOUR_OF_DAY,hour);
    cal.set(Calendar.MINUTE,minutes);
    cal.set(Calendar.SECOND,seconds);

    return cal;
}

任何帮助您查找为什么仅触发一次通知(不仅每天触发一次,而且仅在应用程序首次运行时提供帮助)的帮助。

wish4star 回答:Android:每日定时警报仅触发一次

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3167684.html

大家都在问