Run code every min in foreground service - android

How can I set a timer, within a service that is running in foreground, so it runs a piece of code every 1 min. In pseudo code I want smth like this.
public int onStartCommand(Intent intent, int flags, int startId) {
startEveryMinTask()
return START_STICKY;
}
private void startEveryMinTask() {
//do stuf
}

You can use java.util.Timer
Timer timer = new Timer();
public int onStartCommand(Intent intent, int flags, int startId) {
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
startEveryMinTask();
}, 60000, 60000); // 60000 milliseconds = 1 minute
return START_STICKY;
}

Just Use AlarmManager to shoot an intent to invoke your service again after its done with its code.

Related

Service stops when App stop

When I close App service stops running,
I have tried START_STICKY but still not working.
I need to show notification whenever server respond
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Timer timer = new Timer();
timer.schedule(new Receive(), 0, 5000);
return START_STICKY;
}
Here is my enitre Class
http://justpaste.it/14gqd
you need to bind it with notification. then system allows to run service.
#Override
public int onStartCommand(Intent intent, int flags, int startId){
startForeground(999, bindService()/*function to return notification*/);
return START_REDELIVER_INTENT;
}
and this function to return notification.
protected Notification bindService(){
Notification.Builder mBuilder = new Notification.Builder(this);
/*customize notification builder here*/
return mBuilder.build();
}
Service is Killed As Activity is Destroyed , You might Wanna Look into JobScheduler or use TimerTask(Easy to Implements)
Timer Task Example
#Override
public void onStart(Intent intent, int startId) {
// Perform your long running operations here.
//Creating new thread for service
//Always write your long running tasks in a separate thread, to avoid ANR
final Handler handler = new Handler();
timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
Log.i(TAG, "Service running");
}
});
}
};
timer.scheduleAtFixedRate(task, 0, 10000); // Executes thetask every 5 seconds.

android service timer and sleep mode

I am writing app, which include service and timer. User set time of Timers. Timer must every day make work(even night). Timer (and service) is working when telephone active, but when telephone goes into sleep mode timer doesn't work(service still work).
May be I must use the Handler with timer how here: Android timer? How-to? or I must use PowerManager and forcibly not allowed to sleep telephone?
I use timer within service
public class SampleService extends Service {
....
public int onStartCommand(Intent intent, int flags, int startId) {
my_timer_start();
}
my_timer_start();{
ltimer = new Timer();
ltimer.scheduleAtFixedRate(new My_task(), time1, every_hour);
}
class My_task implements Runnable {
#Override
public void run() {
// TODO Auto-generated method stub
...........................
}
}
void cancel_task() {
ltimer.cancel();
ltimer = null;
}
public void onDestroy() {
super.onDestroy();
cancel_task();
}
}
thanks for the help!

Android service background

I have an Activity that calls startService() in the onCreate() with some params.
The Service works well (I use a Timer) but when I quit the Activity (onPause() or onDestroy()) what happens is that the Service is recreated! It calls onCreate then onStartCommand() with a null intent! (normal)
So how should I do to retrien the old intent?!
I think there's START_REDELIVER_INTENT but how to use it! Is this the right way?
PS: Why the is the Service killed although it extends Service? Does it depend on Lifecycle of the activity => so who called him again?
public class MyService extends Service {
private static Timer timer = new Timer();
#Override
public void onCreate() {
Log.d(TAG, "onCreate");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent != null){
Bundle bundle = intent.getExtras();
if (bundle != null)
{
timer.scheduleAtFixedRate(new Action(),15000 , 15000);
}
}
Action() {
timer = new Timer();
timer.scheduleAtFixedRate(new Action(),15000 , 15000);
}
}
Try to use intentService instead of service
After some research i found the solution and it maybe simple for some, so with reading this: START_STICKY and START_NOT_STICKY and that we won't the service restart itself we should return on the onCommand method START_NOT_STICKY
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO
return START_NOT_STICKY ;
}

Service doesnot stop after activity destroy

I have written a service with timer to do something periodically but when I stop service service from mainActivity if my service is in middle of their task it's continue to finish and after that stop it and the same issue when i want to close application that call OnDestroy on Main Activity service work and after finish their task don't start again.
My Question is how can Force stop service when i want to exit from my app?
this is my service code
public class MyTimerService extends Service{
private static int counter = 0;
private Timer timer = new Timer();
private int INTERVAL;
#Override
public IBinder onBind(Intent i) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
INTERVAL = intent.getIntExtra("time", 500);
repaet();
return START_NOT_STICKY;
}
private void repaet() {
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Log.i("Saeed", String.valueOf(++counter));
}
}, 0, INTERVAL);
}
#Override
public void onDestroy() {
Toast.makeText(this, "Stop Service", Toast.LENGTH_LONG).show();
if(timer!=null){
timer.cancel();
}
stopSelf();
super.onDestroy();
}
}
Have you tried to manually stop your service inside onDestroy() by using this stopService()?

Android: re-starting Timer fails

I'm trying to download some data of a url every X minutes. This is run from a Service.
I have the following in my Service class:
public class CommandsService extends Service {
public String errormgs;
// in miliseconds
static final long DELAY = 60*1000;
public Timer timer;
public int onStartCommand (Intent intent, int flags, int startId) {
TimerTask task= new TimerTask (){
public void run(){
//do what you needs.
processRemoteFile();
// schedule new timer
// following line gives error
timer.schedule(this, DELAY);
}
};
timer = new Timer();
timer.schedule(task, 0);
return START_STICKY;
}
//....
}
Runs fine a first time, but when I try to "schedule" the timer a second time with the DELAY, LogCat complains:
"TimeTask scheduled already"
How could I re-schedule the Timer?
The TimerTask is a single use item. It can't be rescheduled or reused; you'll need to create new instances on the fly as you need them.
How about:
public class CommandsService extends Service {
public String errormgs;
// in miliseconds
static final long DELAY = 60*1000;
public Thread thread;
public int onStartCommand (Intent intent, int flags, int startId) {
Runnable runnable = new Runnable () {
public void run() {
while (<condition>) {
//do what you needs.
processRemoteFile();
try {
Thread.sleep(DELAY);
} catch (InterruptedException e) {
}
}
}
};
thread = new Thread(runnable);
thread.start();
return START_STICKY;
}
//...
}

Categories

Resources