In actual development, do some timing operations
For example, execute a certain code after three minutes
Usually at this time we will first think of Timer
But if this time is longer
For example, to execute after 30 days
Only Timer is not enough.
Here is a quick and convenient way
Is to use the AlarmManager class
System timing service
It is also very simple to use, just cooperate with the broadcast
The specific code is as follows:
//30天以后启动广播
//获取系统服务
AlarmManager manager = (AlarmManager)MyService.this.getSystemService(Activity.ALARM_SERVICE);
//设置定时时长
long anHour = 30l * 60 * 60 * 1000 * 24;//30天以后
long triggerAtTime = System.currentTimeMillis() + anHour;
Intent i = new Intent(MyService.this, TimeReceiver.class);
//发送广播
PendingIntent pi = PendingIntent.getBroadcast(MyService.this, 0, i, 0);
//发送定时消息
manager.set(AlarmManager.RTC, triggerAtTime, pi);
When timing operations are needed
Set the corresponding duration to send the broadcast
Then you can perform the operation in the broadcast by yourself