Service that runs every minute

前端 未结 3 504
借酒劲吻你
借酒劲吻你 2020-12-24 14:33

I have a service that I am wanting to execute a task every minute in the background. It does not need to execute the task whenever the phone is asleep, only when the user is

3条回答
  •  情话喂你
    2020-12-24 14:58

    This will send an intent to your service every minute without using any processor time in your activity in between

      Intent myIntent = new Intent(context, MyServiceReceiver.class);
      PendingIntent pendingIntent = PendingIntent.getBroadcast(context,  0, myIntent, 0);
    
      AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
      Calendar calendar = Calendar.getInstance();
      calendar.setTimeInMillis(System.currentTimeMillis());
      calendar.add(Calendar.SECOND, 60); // first time
      long frequency= 60 * 1000; // in ms 
      alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), frequency, pendingIntent);           
    

    Adjust MyServiceReceiver.class to match your target service or activity. The documentation provides more details to fine-tune your calls like whether you want exact timing, execution at a specific time of the day ...

提交回复
热议问题