I tried the sample of AlarmManager,which in https://developer.android.com/training/scheduling/alarms
My MainActivity.java like this:
alarmMgr = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, BroadcastReciever.class);
alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
// call every 5mins
alarmMgr.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(),
1000 * 60 * 5L, alarmIntent);
My BroadcastReciever.java like this:
public class BroadcastReciever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("Execute time:" + Calendar.getInstance().getTime());
}
}
I hope it output something like "Execute time:Thu Apr 14 17:33:45 GMT+09:00 2022" in every 5mins I installed the app in my physical device and restart the app in my physical device.(device still connect to the PC with an USB cable.)Android studio catch these log below:
2022-04-14 17:33:45.009 13580-13580/? I/com.example.ss: Late-enabling -Xcheck:jni
2022-04-14 17:33:45.050 13580-13580/? E/com.example.ss: Unknown bits set in runtime_flags: 0x8000
2022-04-14 17:33:45.611 13580-13580/com.example.ss I/Perf: Connecting to perf service.
2022-04-14 17:33:45.671 13580-13580/com.example.ss I/System.out: Execute time:Thu Apr 14 17:33:45 GMT+09:00 2022
The first problem is that, it's not output in every 5mins. The second problem is that, sometimes it was output something like these (not in every 5mins)
2022-04-14 11:56:09.145 ...
2022-04-14 11:56:09.150 ...
2022-04-14 11:56:09.154 ...
I need to make a app, which make a new logfile at 0:00 every day.so I try the alarmmanager & broadcastReciever. I need to make sure the logfile only be created one time,(in second case may create three times I guess)
There are dozens of similar questions on Stackoverflow. You really should search before you create a new question.
Basically, setRepeating()
is inexact. In order to conserve battery power, Android will change the actual time the alarm triggers. You have no control over that. If you need exact timing, you should use something like setExact()
instead. This is not a repeating alarm, so if you need a repeating alarm you should do something like this: when the alarm gets triggered, do whatever and then set the next alarm.
You wrote:
I need to make a app, which make a new logfile at 0:00 every day.so I try the alarmmanager & broadcastReciever. I need to make sure the logfile only be created one time,(in second case may create three times I guess)
so you should schedule an alarm with setExact()
for 00:00 of the following day. When that alarm triggers, rotate your logfiles and then set an alarm for 00:00 of the following day. This will ensure that your alarm goes off at the correct time and that it only triggers once per day.