警报通知立即触发。 Android

Alarm Notification fires instantly. Android

我正在开发一个在固定时间向用户发送通知的提醒。

闹钟马上响了...

我尝试了 Whosebug 中的大部分建议,但仍然遇到同样的问题

请帮我解决这个问题。

服务器数据

user_reminder": [
                {
                    "id": "75",
                    "name": "Morning Snacks",
                    "time": "11:00:00",
                    "days": "1,2,3,4,5,6,7",
                    "user_id": "14"
                },
                {
                    "id": "76",
                    "name": "Lunch",
                    "time": "13:00:00",
                    "days": "1,2,3,4,5,6,7",
                    "user_id": "14"
                },
               ......
            ]

我的代码

for (int i = 0; i < reminderList.size(); i++) 
{
     String time = reminderList.get(i).getTime(); // "time": "11:00:00"

    String strSpit[] = time.split(":");
    String strDays[] = reminderList.get(i).getDays().split(","); //"days": "1,2,3,4,5,6,7"

    Date date = new Date();
    Calendar calNow = Calendar.getInstance();
    calNow.setTime(date);

    Calendar calAlarm = Calendar.getInstance();
    calAlarm.set(Calendar.HOUR_OF_DAY, Integer.parseInt(strSpit[0]));
    calAlarm.set(Calendar.MINUTE, Integer.parseInt(strSpit[1]));

    for (int j = 0; j < strDays.length; j++) 
    {
        calAlarm.set(Calendar.DAY_OF_WEEK, viewFunctions.getDayInt(strDays[j]));

        if (calAlarm.before(calNow)) 
        {
            //if its in the past increment
            calAlarm.add(Calendar.DATE, 1);
        }

        notifyIntent.putExtra(Constants.REMINDER_NAME, reminderList.get(i).getName());
        pendingIntent = PendingIntent.getBroadcast(this, 0, notifyIntent, PendingIntent.FLAG_ONE_SHOT);
        alarmManager.set(AlarmManager.RTC_WAKEUP, calAlarm.getTimeInMillis() , pendingIntent);

        }
    }
}

获取天数:这解决了天数

public int getDayInt(String strDay) 
{
   int dayNumber = 0;

   if (strDay.equals("1")) 
   {
       dayNumber = Calendar.MONDAY;

   } ......

   return dayNumber;
}

屏幕截图

问题

您的闹钟会立即响起,因为 Android 会触发过去安排的任何闹钟。

你的一些闹钟是过去安排的,因为以下代码没有按你预期的那样工作。您问题的示例代码:

if (calAlarm.before(calNow)) 
{
   //if [it's] in the past increment
   calAlarm.add(Calendar.DATE, 1);
}

在上面的代码中,如果闹钟是过去的,您只需要将一天添加到闹钟中。因此,假设您在星期五 运行 此代码,并且您阅读了星期一的警报。您的代码会将一天添加到星期二的日期,安排该警报。警报是过去的,因为星期二还在星期五之前,所以 Android 将在安排后不久触发该警报。

更新

从您的问题中不清楚您希望如何处理过去的提醒。一种可能的解决方案是将它们安排在未来 1 周。

if(calAlarm.before(calNow)) 
{
   // If it's in the past increment by one week.
   calAlarm.add(Calendar.DATE, 7);
}

主要问题似乎出在这一行:

calAlarm.set(Calendar.DAY_OF_WEEK, viewFunctions.getDayInt(strDays[j]));

您需要了解的是,这只是设置将在输出中显示的星期几 - 它不会更改基础日期以匹配,我认为这正是您所期望的。

尝试使用以下代码更改您的日期,以便为所选的每一天设置闹钟:

String strSpit[] = time.split(":");
String strDays[] = reminderList.get(i).getDays().split(","); //"days": "1,2,3,4,5,6,7"

Calendar todayWithTime = Calendar.getInstance(); //setting current time is redundant
todayWithTime.set(Calendar.HOUR_OF_DAY, Integer.parseInt(strSpit[0]));
todayWithTime.set(Calendar.MINUTE, Integer.parseInt(strSpit[1]));

Calendar alarm;
int today = todayWithTime.get(Calendar.DAY_OF_WEEK);
int offset, target;

for (int j = 0; j < strDays.length; j++) {

    alarm = (Calendar) todayWithTime.clone(); //now you have todays date, but correct time
    target = strDays[j];
    //saturday is biggest day of week
    offset  = (Calendar.SATURDAY - today + target) % 7; //work out how many days in the future the next occurance of this day is
    alarm.add(Calendar.DATE, offset);

    ... // the rest stays the same

}

我之前也遇到过同样的问题,请查看以下详情:

无效代码示例:

Intent notificationIntent = new Intent("~~~.BaseActivity");
        notificationIntent.putExtra("type", 2);
        notificationIntent.putExtra("appName", "testApp");
        notificationIntent.putExtra("messageEN", "Good evening");
        notificationIntent.putExtra("notificaitonID", 4);


        PendingIntent broadcast = PendingIntent.getBroadcast(context, 4,
                notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 18);
        calendar.set(Calendar.MINUTE, 10);
        calendar.set(Calendar.SECOND, 0);
        // this is to show it at the 6:10 

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);



        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                    calendar.getTimeInMillis(),
                    AlarmManager.INTERVAL_DAY,
                    broadcast);

工作代码:

    Intent notificationIntent = new Intent("~~~.BaseActivity");
    notificationIntent.putExtra("type", 2);
    notificationIntent.putExtra("appName", "testApp");
    notificationIntent.putExtra("messageEN", "Good evening");
    notificationIntent.putExtra("notificaitonID", 4);


    PendingIntent broadcast = PendingIntent.getBroadcast(context, 4,
            notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 18);
    calendar.set(Calendar.MINUTE, 10);
    calendar.set(Calendar.SECOND, 0);
    // this is to show it at the 6:10 

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);


    Calendar nowCalendar = Calendar.getInstance();

    if (calendar.after(nowCalendar)) {
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                calendar.getTimeInMillis(),
                AlarmManager.INTERVAL_DAY,
                broadcast);

    } else {
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                calendar.getTimeInMillis(),
                AlarmManager.INTERVAL_DAY,
                broadcast);
    }

只有当你要设置重复的时候才完成,你需要检查它是否通过,如果通过就添加想要的重复时间

最后我找到了一种方法,将 PendingIntent requestCode 存储在数据库(使用过的 ROOM)中,然后通过从 DB[=19 中检索所有 requestCode 来取消所有警报=]

AlarmIdPojo

@Entity
public class AlarmIdPojo {

    @PrimaryKey(autoGenerate = true)
    public int id;

    private int requestCode;

    public AlarmIdPojo() {
    }

    public int getRequestCode() {
        return requestCode;
    }

    public void setRequestCode(int requestCode) {
        this.requestCode = requestCode;
    }
}

AlarmIdDAO

@Dao
public interface AlarmIdDAO {

    @Query("select * from AlarmIdPojo")
    List<AlarmIdPojo> getAllRequestCode();

    @Query("delete from AlarmIdPojo")
    public void deleteAllRequestCode();

    @Insert(onConflict = REPLACE)
    void addRequestCode(AlarmIdPojo pojo);
}

AppDatabase

@Database(entities = {AlarmIdPojo.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {

    public abstract AlarmIdDAO requestIdPojo();

    @Override
    protected SupportSQLiteOpenHelper createOpenHelper(DatabaseConfiguration config) {
        return null;
    }

    @Override
    protected InvalidationTracker createInvalidationTracker() {
        return null;
    }
}

来电提醒

private void callReminder() {


        //  java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
        // because of this Exception , we are doing this in AsyncTask

        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                List<AlarmIdPojo> idList = appDatabase.requestIdPojo().getAllRequestCode();

                Intent notifyIntent = new Intent(MainActivity.this, MyReceiver.class);
                AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                PendingIntent pendingIntent;

                for (int i = 0; i < idList.size(); i++) {


                    int requestId = idList.get(i).getRequestCode();

                    pendingIntent = PendingIntent.getBroadcast(MainActivity.this, requestId, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);

                    // Cancel alarms
                    try {
                        alarmManager.cancel(pendingIntent);
                    } catch (Exception e) {
                        Log.e(TAG, "AlarmManager update was not canceled. " + e.toString());
                    }

                }

                appDatabase.requestIdPojo().deleteAllRequestCode();
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);

                // Once every request code is deleted , then once again call setReminderNotification() for fresh data.
                setReminderNotification();

            }
        }.execute();


    }

setReminderNotification

private void setReminderNotification() {

        Intent notifyIntent = new Intent(this, MyReceiver.class);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        PendingIntent pendingIntent;


        // Taking existing offline reminder data from sharePreference
        Type type = new TypeToken<List<UserReminderPojo>>() {
        }.getType();
        List<UserReminderPojo> reminderList = new Gson().fromJson(sharedPrefUtils.getString(sharedPrefUtils.DEFAULT_REMINDERS), type);


        for (int i = 0; i < reminderList.size(); i++) {

            String time = reminderList.get(i).getTime();

            String strSpit[] = time.split(":");

            String strDays[] = reminderList.get(i).getDays().split(",");


            Calendar todayWithTime = Calendar.getInstance();
            todayWithTime.set(Calendar.SECOND, 0);
            todayWithTime.set(Calendar.MILLISECOND, 0);


            for (int j = 0; j < strDays.length; j++) {

                Calendar alarm = Calendar.getInstance();
                alarm.set(Calendar.SECOND, 0);
                alarm.set(Calendar.MILLISECOND, 0);

                alarm.set(Calendar.HOUR_OF_DAY, Integer.parseInt(strSpit[0]));
                alarm.set(Calendar.MINUTE, Integer.parseInt(strSpit[1]));
                alarm.set(Calendar.DAY_OF_WEEK, viewFunctions.getDayInt(strDays[j]));


                int randomPendingIntentId = generateRandomId();
                notifyIntent.putExtra(Constants.REMINDER_NAME, reminderList.get(i).getName());
                notifyIntent.putExtra(Constants.ID, randomPendingIntentId); // passing it , so that we can cancel this PendingIntent with this Id, once notification is shown.This is done to prevent past time alarm firing
                notifyIntent.putExtra(Constants.REMINDER_DAY, viewFunctions.getDayInt(strDays[j]));
                pendingIntent = PendingIntent.getBroadcast(this, randomPendingIntentId, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);

                if (alarm.before(todayWithTime)) {
                    alarm.add(Calendar.DATE, 7);
                }

                alarmManager.set(AlarmManager.RTC_WAKEUP, alarm.getTimeInMillis(), pendingIntent);

                insertToDB(randomPendingIntentId);

            }
        }

    }

insertToDB

// Saving to DB. keeping track  of PendingIntent unique id.
    private void insertToDB(int randomPendingIntentId) {
        alarmIdPojo = new AlarmIdPojo();
        alarmIdPojo.setRequestCode(randomPendingIntentId);

        //  java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
        // because of this Exception , we are doing this in AsyncTask

        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                appDatabase.requestIdPojo().addRequestCode(alarmIdPojo);
                return null;
            }
        }.execute();

    }

遇到同样的问题,在寻找解决方案时偶然发现了这个问题。 设置闹钟时,您只需要检查您的闹钟日期不应早于当前日期。

public static void setReminder(Context context,Class<?> cls,long milliseconds, int event_id,String eventName)
{
    Calendar calendar = Calendar.getInstance();

    Calendar notificationcalendar = Calendar.getInstance();

    notificationcalendar.setTimeInMillis(milliseconds);

    if(!notificationcalendar.before(calendar)) { // **just add this check**


        ComponentName receiver = new ComponentName(context, cls);
        PackageManager pm = context.getPackageManager();

        pm.setComponentEnabledSetting(receiver,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);


        Intent intent1 = new Intent(context, cls);
        intent1.putExtra("eventName", eventName);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, event_id, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
        am.setInexactRepeating(AlarmManager.RTC_WAKEUP, notificationcalendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
    }

}