Service that repeatedly runs a method, after an amount of time

前端 未结 1 1081
无人及你
无人及你 2020-12-10 09:39

I want to create a service, that runs a method after 10 seconds over and over again, until I stop it, even if the app is closed. My attempted code is below

p         


        
相关标签:
1条回答
  • 2020-12-10 10:23

    create a broadcast receiver that will start your service after receiving broadcast from AlarmManager :

    public class SyncAlarm extends BroadcastReceiver {
    
    @Override
    public void onReceive(Context context, Intent data) {
    
        // set alarm to start service
        Calendar calendar = new GregorianCalendar();
        calendar.setTimeInMillis(System.currentTimeMillis());
    
        Calendar cal = new GregorianCalendar();
        cal.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR));
        cal.set(Calendar.HOUR_OF_DAY,  calendar.get(Calendar.HOUR_OF_DAY));
    
        // start service after an hour
        cal.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) + 60);
        cal.set(Calendar.SECOND, calendar.get(Calendar.SECOND));
        cal.set(Calendar.MILLISECOND, calendar.get(Calendar.MILLISECOND));
        cal.set(Calendar.DATE, calendar.get(Calendar.DATE));
        cal.set(Calendar.MONTH, calendar.get(Calendar.MONTH));
    
        // set alarm to start service again after receiving broadcast
        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, SyncAlarm.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        am.cancel(pendingIntent);
        am.set(AlarmManager.RTC, cal.getTimeInMillis(), pendingIntent);
    
        intent = new Intent(context, Reminder.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startService(intent);
        }
    }
    

    start your broadcast receiver for the first time when you start your application:

        AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, SyncAlarm.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        am.cancel(pendingIntent);
        am.set(AlarmManager.RTC, System.currentTimeMillis(), pendingIntent);
    

    Also add this to your Manifest File:

    <receiver android:name=".SyncAlarm" >
    </receiver>
    

    You should also have alook at this START_STICKY if you want your service to be started by Android system as soon as resources are available instead of receiving Broadcast by AlarmManager.

    0 讨论(0)
提交回复
热议问题