警报通知立即触发.Android的

kar*_*nji 8 notifications android alarmmanager

我正在开发一个提醒,它会在固定时间向用户发送通知.

警报瞬间下降......

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

请帮我解决这个问题.

服务器数据

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"
                },
               ......
            ]
Run Code Online (Sandbox Code Playgroud)

我的代码

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

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

获取日期:这解决了日期编号问题

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

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

   } ......

   return dayNumber;
}
Run Code Online (Sandbox Code Playgroud)

屏幕截图

在此输入图像描述

kar*_*nji -1

最后我找到了一种方法来做到这一点,方法是存储在数据库(使用的房间)中,然后通过检索所有来自的PendingIntent requestCode警报来取消所有警报requestCodeDB

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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);
}
Run Code Online (Sandbox Code Playgroud)

应用数据库

@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;
    }
}
Run Code Online (Sandbox Code Playgroud)

来电提醒

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


    }
Run Code Online (Sandbox Code Playgroud)

设置提醒通知

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

            }
        }

    }
Run Code Online (Sandbox Code Playgroud)

插入数据库

// 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();

    }
Run Code Online (Sandbox Code Playgroud)