在我的应用程序中,我需要在用户在应用程序中执行某些操作后 1 周或 1 个月后发送通知...它正在与这样的 BroadcastReceiver 一起使用 >>
public void startMyReceiver() {
Long time = new GregorianCalendar().getTimeInMillis() + 1000 * 60 * 60 * 24 * 30; <-- for 1 month (it's getting numeric overflow, but is working)
Long interval = 2592000000L;
Intent intentAlarm = new Intent(this, MyReceiver.class);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, interval, PendingIntent.getBroadcast(this, 2, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
}
然后是简单的接收器类>>
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent){
sendNotification();
{
}
然后在AndroidManifest.xml中>>
<application>
<receiver android:name="mypackage.MyReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
我设置了“android.intent.action.BOOT_COMPLETED”,认为它将恢复计数器并继续计数直到时间结束...
但是当设备启动时它会立即启动我的接收器...
如何将接收器设置为 1 个月并在重新启动后继续计数?
-- 编辑 -- 新问题 --
存储时间和进行计算的最简单方法是什么?像这样的东西?? >>
1 - 第一次定义闹钟时,我将当前时间(以毫秒为单位)保存在 Long firstTime 中,并将闹钟定义为firstTime+longOneMonth;
2 - 在启动接收器中,我再次获取当前时间并将其保存在长重新启动时间中,然后我执行以下操作:
Long timeDifference = rebootTime - firstTime;
Long differenceToMonth = longOneMonth - timeDifference;
并再次将接收器设置为时间rebootTime + DifferenceToMonth??
-- 编辑 2--
也许如果我将第一个接收器设置毫秒转换为日期字符串并将其 apply() 到共享首选项,则重新启动时,我可以再次将其转换为毫秒...我想它会起作用并且更容易
最佳答案
- 定义另一个用于启动的广播接收器。
- 将时间(一个月后)存储在某个地方
- 设备启动时,所有闹钟都会消失。因此,当设备启动时,调用另一个函数来再次设置闹钟。但请注意,您应该考虑到自上次设置闹钟以来已经过去了一段时间(例如 7 天前您设置闹钟),因此您应该始终计算设置时间与当前时间之间的差异;
编辑: 计算时间的最简单方法是,当您设置闹钟时,将当前时间存储为毫秒。下次您再次获得现在时间并将其减去您上次存储的时间。这就是时差!
最后减去一个月的时间差值
Long time =
new GregorianCalendar().getTimeInMillis() +
( 1000 * 60 * 60 * 24 * 30 ) -
TIME_DIFFERENCE
关于java - 重启后恢复报警计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40581334/