0

Hello i want to make a background service to update the data of my app and repeat it once a day, also i want the service to start onboot. I have the following code:

public class OnBoot extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // Create Intent
        context.startService(new Intent(context, BackgroundServiceHandler.class));
    }

}

I have a settings menu so the user can choose the hour of the repeating alarm. How can i reset the time of the alarmmanager? Where i have to put the code of the alarm manager? Do i have to use service or intentservice? How to check if service is running?

Alarm manager code:

    Intent intent = new Intent(MainActivity.this, AlarmService.class);
    intent.putExtra("i", 3);
    PendingIntent pi = PendingIntent.getService(MainActivity.this, 9, intent, 0);

    // every day at 9 am
    Calendar calendar = Calendar.getInstance();

    // if it's after or equal 9 am schedule for next day
    if (Calendar.getInstance().get(Calendar.HOUR_OF_DAY) >= 9) {
        calendar.add(Calendar.DAY_OF_YEAR, 1); // add, not set!
    }
    calendar.set(Calendar.HOUR_OF_DAY, 9);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);

    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

    alarmManager.setInexactRepeating(AlarmManager.RTC, calendar.getTimeInMillis(),
            AlarmManager.INTERVAL_DAY, pi);
Panayiotis Irakleous
  • 2,696
  • 1
  • 23
  • 36

1 Answers1

0
  • How can i reset the time of the alarmmanager?

How to edit/reset Alarm Manager?

  • Where i have to put the code of the alarm manager?

For example you can place that code in static method and call it from place where user set time and from OnBootReceiver. How to implement class which will receive event OnBoot please check that answer.

  • Do i have to use service or intentservice?

Service vs IntentService

  • How to check if service is running?

Check if service is running on Android?

Community
  • 1
  • 1
Divers
  • 9,531
  • 7
  • 45
  • 88