I have a Helper
class and method where I download mails via javamail. It's working fine inside AsyncTask
.
Now I want to implement background service which will be able to:
- run on demand
- run periodically if not running on demand
- has a method where I can know it's ended
- work both inside and outside the application (for example I press the refresh button and the same service is called)
I currently have created a Service
with ScheduledThreadPoolExecutor
and I can run that periodically (every 5 minutes). I just don't know how to run that on demand.
Should I use an Intent
service, just Service
, or even SyncAdapter
s? What would be the best option?
This is what I have so far:
public class BackgroundLoadingService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
executor.scheduleAtFixedRate( new Runnable() {
@Override
public void run() {
Log.i("LocalService", "onCreate");
if (isOnline(BackgroundLoadingService.this))
{
getEmails(BackgroundLoadingService.this,"test",true);
}
}
}, 1, 60*5, TimeUnit.SECONDS );
super.onCreate();
}
@Override
public int onStartCommand( final Intent intent, final int flags, final int startId ) {
Log.i("LocalService", "onstartcommand");
return Service.START_STICKY;
}
}