Panayiotis Irakleous
Panayiotis Irakleous

Reputation: 2696

Background service with repeat time

Hello i want to create a background service that will repeat at specific time each day to update the data from server, and until now i have this code:

public class Service_class extends Service {


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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
    return START_STICKY;
}

@Override
public void onDestroy() {

    super.onDestroy();
    Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();

}

@Override
public void onCreate() {
    super.onCreate();
}

}

and i start the service with this code in main

startService(new Intent(getBaseContext(), Service_class.class));

How can i make this service repeat at exact time each day and never stop even if the app is closed? Thank you

Upvotes: 0

Views: 1079

Answers (3)

ashishmaurya
ashishmaurya

Reputation: 1196

You can use AlarmManager class for this

Intent alarmIntent = new Intent(context, Service_class.class);
    pendingIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
    AlarmManager manager = (AlarmManager) context
            .getSystemService(Context.ALARM_SERVICE);
    int interval = 60*60*24;//number of seconds
    manager.setInexactRepeating(AlarmManager.RTC_WAKEUP,
            System.currentTimeMillis(), interval, pendingIntent);

Upvotes: 0

Sachin salunkhe
Sachin salunkhe

Reputation: 100

You can use AlaramManager like below

AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

Intent i = new Intent(context, Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (1000 * 60 * 10), pi); 

// Millisec * Second

Upvotes: 1

JVN
JVN

Reputation: 239

I too had this same requirement.i followed the below procedure. In your service's onCreate()

Intent alarmIntent=new Intent(this,AlarmHandle.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
int interval = 86400*1000; // for getting called every 24 hours 
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);

Here the AlarmHandle class extends BroadcastReceiver. The onReceive of this receiver will get called during the time interval value mentioned.

Make sure the AlarmHandle is mentioned with receiver tag in the AndroidManifest file.

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

Upvotes: 0

Related Questions