I have a BroadcastReceiver starting a service. In this service I have an AlarmManager I want to start another service at a certain time of day, every day.
The BroadcastReceiver starts when I open the app, but the AlarmManager only starts its service if I start the BroadCastReceiver at the set time.
How do I get it to continuously compare the present time to the set time, so that it will automatically run when the time is right?
In MainActivity.java
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent();
intent.setAction("com.example.BroadcastPro.MyBroadcastReceiver");
sendBroadcast(intent);
}
In myBroadcastReceiver.java
public class MyBroadcastReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Intent i=new Intent(context,SetPeriodicService.class);
context.startService(i);
}
}
In SetPeriodicService.java
public int onStartCommand(Intent intent, int flags, int startId)
{
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 30);
Intent i=new Intent(this,MyService.class);
PendingIntent alarmIntent = PendingIntent.getService(this, 0, i, 0);
AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmManager.INTERVAL_DAY, alarmIntent);
return super.onStartCommand(intent, flags, startId);
}
In SetPeriodicService.java at alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmManager.INTERVAL_DAY, alarmIntent);
You need change to alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmMgr.INTERVAL_DAY, alarmIntent);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.