我正在处理一个提醒,它会在固定时间向用户发送通知。
警报立即起飞......
我尝试了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"
},
......
]
我的代码
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;
}
屏幕截图
答案 0 :(得分:1)
主要问题似乎是这一行:
' Shows and hides the multiple option UserForm
MultipleOptionForm.Show
MultipleOptionForm.Hide
' Creates an array from a comma-delimited
' list of numbers stored in a variable
MFA = Split(MultFLNAmt, ",")
' Activates the application we will be assigning work from
WShell.AppActivate "Non-Keyable Document Management System"
' Table cell node where the dropdown is located
tdNode = 64
a = 1
' Loop through each of the names within the array
For c = LBound(MyArray) + 1 To UBound(MyArray) - 1
' Loop through the array to see how many FLNs each person receives
For b = 1 To MFA(a)
' Loop through to locate the current name of the employee
i = 0
For Each objOption In objIE.Document.GetElementsByTagName("table")(0).GetElementsByTagName("td")(tdNode).GetElementsByClassName("txt_input1")(0).Options
Q(i) = objOption.Text & "-" & objOption.Value
strWQ = Q(i)
' Remove "Selected User" from the list of options
If i = 0 Then
If strWQ = "--Select User---" Then strWQ = ""
Else
' If an option matches the current name selected,
' select that option, then increase the node location
' for the next dropdown box
If InStr(strWQ, MyArray(c)) Then
objOption.Selected = True
objIE.Document.GetElementsByTagName("table")(0).GetElementsByTagName("td")(tdNode).GetElementsByClassName("txt_input1")(0).OnChange
tdNode = tdNode + 23
Else
objOption.Selected = False
End If
End If
Next
i = i + 1
Next
Next
objIE.Document.all.Item("btn_submit1").Click
您需要意识到的是,这只是设置将在输出中显示的星期几 - 它不会更改要匹配的基础日期,我认为这是您期望的。
尝试使用以下代码更改日期,为所选的每一天设置闹钟:
MFA(a)
答案 1 :(得分:0)
您的闹钟会立即响起,因为Android会触发过去安排的所有闹钟。
您的某些警报过去已安排,因为以下代码无法按预期运行。您问题的示例代码:
if (calAlarm.before(calNow))
{
//if [it's] in the past increment
calAlarm.add(Calendar.DATE, 1);
}
在上面的代码中,如果警报过去,您只需在警报中添加一天。所以,让我们假设您在星期五运行此代码并且您在周一阅读了警报。您的代码将在星期二的日期添加一天,安排该警报。警报已经过去,因为星期二仍然在星期五之前,因此Android将在安排后不久发出警报。
从您的问题中不清楚您希望如何处理过去的提醒。一种可能的解决方案是在未来一周安排它们。
if(calAlarm.before(calNow))
{
// If it's in the past increment by one week.
calAlarm.add(Calendar.DATE, 7);
}
答案 2 :(得分:0)
我之前有同样的问题,请查看以下详细信息:
不能使用代码示例:
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);
}
只有当您要设置重复时,才需要检查它是否通过,如果通过则只需添加重复所需的时间
答案 3 :(得分:0)
在找到解决方案时遇到了同样的问题,偶然发现了这个问题。 设置闹钟时,您只需要检查一下闹钟日期就不能早于当前日期。
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);
}
}
答案 4 :(得分:-1)
最后,我找到了一种方法,将PendingIntent requestCode
存储在数据库(使用过的ROOM)中,然后通过从requestCode
检索所有DB
来取消所有警报
<强> 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;
}
}
<强> callReminder 强>
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();
}