ebrahim babavand
ebrahim babavand

Reputation: 119

start a service with Alarmmanager at specific date and time and Repeating

I want to create reminder app

I have searched a lot of places but couldnt find a clean sequential explanation of how to start a service (or if thats not possible then an activity) at a specific time daily using the AlarmManager?

i want start service at specific date and time and for example Six months after that date start the service again And continue this cycle

Calendar cur_cal = new GregorianCalendar();
cur_cal.setTimeInMillis(System.currentTimeMillis());//set the current time and date for this calendar

Calendar cal = new GregorianCalendar();
cal.add(Calendar.YEAR, 2018);
cal.set(Calendar.MONTH, 2);
cal.set(Calendar.DAY_OF_MONTH, 12);
cal.set(Calendar.HOUR_OF_DAY, 9);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);

Intent intent = new Intent(ProfileList.this, BroadcastedReceiver.class);
PendingIntent pintent = PendingIntent.getService(ProfileList.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000, pintent);

i tried this code to activate the alarm at 2018-02/12 9:00... this is Works on this date but i have problem to repeating after for example six month...How do I change the codes to be start service every six months?

NOTE: Dates are stored in the database And they will be called from there

Upvotes: 3

Views: 1806

Answers (2)

MarGin
MarGin

Reputation: 2518

it's better to use job scheduler or firebase dispatcher for your requirement

refer this links https://medium.com/google-developers/scheduling-jobs-like-a-pro-with-jobscheduler-286ef8510129

https://github.com/firebase/firebase-jobdispatcher-android

Upvotes: 0

matin sayyad
matin sayyad

Reputation: 595

    public class AddService extends Service
    {
        InterstitialAd mInterstitialAd;
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
           //Your Logic
            stopSelf();
            return START_NOT_STICKY;
        }

        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }

        @Override
        public void onDestroy() {
            AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
            alarmManager.set(alarmManager.RTC_WAKEUP, System.currentTimeMillis() + (1000*60*60),
                    PendingIntent.getService(this,0,new Intent(this,AddService.class),0));
        }
    }

// Here your service will call every 1 hour, you can change time according to that

Upvotes: 1

Related Questions