Android foreground service slow if device is idle










5















I have an android foreground service, called with the notification.
In the service Im just logging every 10 seconds "Tick tack", but the priority of the service is navigate in a webview every X seconds, so Im using new threads and working in the main thread too.



If I have the app connected to the usb the logs seems ok, the "tick tack" is called every 10 seconds, same if the mobile is unlocked and Im wathing the logs on the app.



But when I disconnect the usb, or I lock the device this is what is happening:



2018-11-14 12:11:53.115 12596-12596/? I/Service: tick tack
2018-11-14 12:12:18.704 12596-12596/? I/Service: tick tack
2018-11-14 12:15:42.572 12596-12596/? I/Service: tick tack
2018-11-14 12:17:30.942 12596-12596/? I/Service: tick tack
2018-11-14 12:17:53.534 12596-12596/? I/Service: tick tack
2018-11-14 12:18:27.118 12596-12596/? I/Service: tick tack
2018-11-14 12:18:37.118 12596-12596/? I/Service: tick tack
2018-11-14 12:18:47.118 12596-12596/? I/Service: tick tack
2018-11-14 12:18:57.121 12596-12596/? I/Service: tick tack
2018-11-14 12:19:25.208 12596-12596/? I/Service: tick tack
2018-11-14 12:19:48.294 12596-12596/? I/Service: tick tack


What is the limit of foreground services? Can I do hard foreground work even the device is idle?










share|improve this question
























  • What are you using as a timer?

    – PPartisan
    Nov 14 '18 at 11:50











  • Please describe your usecase and how you start the service and what loops the "tick tack".

    – peceps
    Nov 14 '18 at 11:50











  • @peceps Im starting the service from a push notification, with context.startForegroundService, in the onCreate of the servie I send the notification, the usecase is to report the status of some foreground process, but isnt working

    – Pablo Cegarra
    Nov 14 '18 at 11:52











  • @PPartisan is a countDownTimer, but the service does more things, but seems that it isnt working as expected

    – Pablo Cegarra
    Nov 14 '18 at 11:54







  • 1





    A wake lock is most likely the solution to this problem. If that's not working, that could be because of deep doze, or your wake lock was finalize()'d unexpectedly due to an incorrect scope.

    – greeble31
    Nov 18 '18 at 12:34
















5















I have an android foreground service, called with the notification.
In the service Im just logging every 10 seconds "Tick tack", but the priority of the service is navigate in a webview every X seconds, so Im using new threads and working in the main thread too.



If I have the app connected to the usb the logs seems ok, the "tick tack" is called every 10 seconds, same if the mobile is unlocked and Im wathing the logs on the app.



But when I disconnect the usb, or I lock the device this is what is happening:



2018-11-14 12:11:53.115 12596-12596/? I/Service: tick tack
2018-11-14 12:12:18.704 12596-12596/? I/Service: tick tack
2018-11-14 12:15:42.572 12596-12596/? I/Service: tick tack
2018-11-14 12:17:30.942 12596-12596/? I/Service: tick tack
2018-11-14 12:17:53.534 12596-12596/? I/Service: tick tack
2018-11-14 12:18:27.118 12596-12596/? I/Service: tick tack
2018-11-14 12:18:37.118 12596-12596/? I/Service: tick tack
2018-11-14 12:18:47.118 12596-12596/? I/Service: tick tack
2018-11-14 12:18:57.121 12596-12596/? I/Service: tick tack
2018-11-14 12:19:25.208 12596-12596/? I/Service: tick tack
2018-11-14 12:19:48.294 12596-12596/? I/Service: tick tack


What is the limit of foreground services? Can I do hard foreground work even the device is idle?










share|improve this question
























  • What are you using as a timer?

    – PPartisan
    Nov 14 '18 at 11:50











  • Please describe your usecase and how you start the service and what loops the "tick tack".

    – peceps
    Nov 14 '18 at 11:50











  • @peceps Im starting the service from a push notification, with context.startForegroundService, in the onCreate of the servie I send the notification, the usecase is to report the status of some foreground process, but isnt working

    – Pablo Cegarra
    Nov 14 '18 at 11:52











  • @PPartisan is a countDownTimer, but the service does more things, but seems that it isnt working as expected

    – Pablo Cegarra
    Nov 14 '18 at 11:54







  • 1





    A wake lock is most likely the solution to this problem. If that's not working, that could be because of deep doze, or your wake lock was finalize()'d unexpectedly due to an incorrect scope.

    – greeble31
    Nov 18 '18 at 12:34














5












5








5


4






I have an android foreground service, called with the notification.
In the service Im just logging every 10 seconds "Tick tack", but the priority of the service is navigate in a webview every X seconds, so Im using new threads and working in the main thread too.



If I have the app connected to the usb the logs seems ok, the "tick tack" is called every 10 seconds, same if the mobile is unlocked and Im wathing the logs on the app.



But when I disconnect the usb, or I lock the device this is what is happening:



2018-11-14 12:11:53.115 12596-12596/? I/Service: tick tack
2018-11-14 12:12:18.704 12596-12596/? I/Service: tick tack
2018-11-14 12:15:42.572 12596-12596/? I/Service: tick tack
2018-11-14 12:17:30.942 12596-12596/? I/Service: tick tack
2018-11-14 12:17:53.534 12596-12596/? I/Service: tick tack
2018-11-14 12:18:27.118 12596-12596/? I/Service: tick tack
2018-11-14 12:18:37.118 12596-12596/? I/Service: tick tack
2018-11-14 12:18:47.118 12596-12596/? I/Service: tick tack
2018-11-14 12:18:57.121 12596-12596/? I/Service: tick tack
2018-11-14 12:19:25.208 12596-12596/? I/Service: tick tack
2018-11-14 12:19:48.294 12596-12596/? I/Service: tick tack


What is the limit of foreground services? Can I do hard foreground work even the device is idle?










share|improve this question
















I have an android foreground service, called with the notification.
In the service Im just logging every 10 seconds "Tick tack", but the priority of the service is navigate in a webview every X seconds, so Im using new threads and working in the main thread too.



If I have the app connected to the usb the logs seems ok, the "tick tack" is called every 10 seconds, same if the mobile is unlocked and Im wathing the logs on the app.



But when I disconnect the usb, or I lock the device this is what is happening:



2018-11-14 12:11:53.115 12596-12596/? I/Service: tick tack
2018-11-14 12:12:18.704 12596-12596/? I/Service: tick tack
2018-11-14 12:15:42.572 12596-12596/? I/Service: tick tack
2018-11-14 12:17:30.942 12596-12596/? I/Service: tick tack
2018-11-14 12:17:53.534 12596-12596/? I/Service: tick tack
2018-11-14 12:18:27.118 12596-12596/? I/Service: tick tack
2018-11-14 12:18:37.118 12596-12596/? I/Service: tick tack
2018-11-14 12:18:47.118 12596-12596/? I/Service: tick tack
2018-11-14 12:18:57.121 12596-12596/? I/Service: tick tack
2018-11-14 12:19:25.208 12596-12596/? I/Service: tick tack
2018-11-14 12:19:48.294 12596-12596/? I/Service: tick tack


What is the limit of foreground services? Can I do hard foreground work even the device is idle?







android android-service






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 16 '18 at 18:17







Pablo Cegarra

















asked Nov 14 '18 at 11:48









Pablo CegarraPablo Cegarra

3,11032744




3,11032744












  • What are you using as a timer?

    – PPartisan
    Nov 14 '18 at 11:50











  • Please describe your usecase and how you start the service and what loops the "tick tack".

    – peceps
    Nov 14 '18 at 11:50











  • @peceps Im starting the service from a push notification, with context.startForegroundService, in the onCreate of the servie I send the notification, the usecase is to report the status of some foreground process, but isnt working

    – Pablo Cegarra
    Nov 14 '18 at 11:52











  • @PPartisan is a countDownTimer, but the service does more things, but seems that it isnt working as expected

    – Pablo Cegarra
    Nov 14 '18 at 11:54







  • 1





    A wake lock is most likely the solution to this problem. If that's not working, that could be because of deep doze, or your wake lock was finalize()'d unexpectedly due to an incorrect scope.

    – greeble31
    Nov 18 '18 at 12:34


















  • What are you using as a timer?

    – PPartisan
    Nov 14 '18 at 11:50











  • Please describe your usecase and how you start the service and what loops the "tick tack".

    – peceps
    Nov 14 '18 at 11:50











  • @peceps Im starting the service from a push notification, with context.startForegroundService, in the onCreate of the servie I send the notification, the usecase is to report the status of some foreground process, but isnt working

    – Pablo Cegarra
    Nov 14 '18 at 11:52











  • @PPartisan is a countDownTimer, but the service does more things, but seems that it isnt working as expected

    – Pablo Cegarra
    Nov 14 '18 at 11:54







  • 1





    A wake lock is most likely the solution to this problem. If that's not working, that could be because of deep doze, or your wake lock was finalize()'d unexpectedly due to an incorrect scope.

    – greeble31
    Nov 18 '18 at 12:34

















What are you using as a timer?

– PPartisan
Nov 14 '18 at 11:50





What are you using as a timer?

– PPartisan
Nov 14 '18 at 11:50













Please describe your usecase and how you start the service and what loops the "tick tack".

– peceps
Nov 14 '18 at 11:50





Please describe your usecase and how you start the service and what loops the "tick tack".

– peceps
Nov 14 '18 at 11:50













@peceps Im starting the service from a push notification, with context.startForegroundService, in the onCreate of the servie I send the notification, the usecase is to report the status of some foreground process, but isnt working

– Pablo Cegarra
Nov 14 '18 at 11:52





@peceps Im starting the service from a push notification, with context.startForegroundService, in the onCreate of the servie I send the notification, the usecase is to report the status of some foreground process, but isnt working

– Pablo Cegarra
Nov 14 '18 at 11:52













@PPartisan is a countDownTimer, but the service does more things, but seems that it isnt working as expected

– Pablo Cegarra
Nov 14 '18 at 11:54






@PPartisan is a countDownTimer, but the service does more things, but seems that it isnt working as expected

– Pablo Cegarra
Nov 14 '18 at 11:54





1




1





A wake lock is most likely the solution to this problem. If that's not working, that could be because of deep doze, or your wake lock was finalize()'d unexpectedly due to an incorrect scope.

– greeble31
Nov 18 '18 at 12:34






A wake lock is most likely the solution to this problem. If that's not working, that could be because of deep doze, or your wake lock was finalize()'d unexpectedly due to an incorrect scope.

– greeble31
Nov 18 '18 at 12:34













1 Answer
1






active

oldest

votes


















0














I have made this library the other day for something similar service in background and foreground



And its working absolutely fine with no problems.



The reason I choose to run it with AlarmManager is that the AlarmManager is a great candidate for scheduling if an application needs to perform a local event + allows an application to schedule tasks that may need to run or repeat beyond the scope of its lifecycle. This allows the application to perform some function even after the application process or all of its Android components have been cleaned up by the system.



UPDATE



Call this method to start the service



 public void call(int Value_in_seconds) 
if (Value_in_seconds == (int) Value_in_seconds)
// Number is integer
Long time = new GregorianCalendar().getTimeInMillis() + Value_in_seconds * 1000;
// create an Intent and set the class which will execute when Alarm triggers, here
// ServiceReciever in the Intent, the onRecieve() method of this class will execute when
// alarm triggers
Intent intentAlarm = new Intent(context, ServiceReciever.class);
// create the object
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
//set the alarm for particular time
alarmManager.set(AlarmManager.RTC_WAKEUP, time, PendingIntent.getBroadcast(context, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
else
Toast.makeText(context, context.getString(R.string.intValue), Toast.LENGTH_SHORT).show();




Create ServiceReciever Class



public class ServiceReciever extends BroadcastReceiver 

@Override
public void onReceive(Context context, Intent intent)
//call the method here





inside your manifest



<application>
<receiver android:name="hossamscott.com.github.backgroundservice.ServiceReciever" android:process=":ff" android:exported="true" android:enabled="true">
</receiver>

<service android:name="hossamscott.com.github.backgroundservice.BackgroundTask"/>

</application>


And thats should be it, tho if you like to run it in Thread
Than you can add the next lines



public class BackgroundTask extends Service 

private boolean isRunning;
private Context context;
private Thread backgroundThread;


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


@Override
public void onCreate()
this.context = this;
this.isRunning = false;
this.backgroundThread = new Thread(myTask);


private Runnable myTask = new Runnable()
public void run()
// Do something here
new Handler(Looper.getMainLooper()).post(new Runnable()
@Override
public void run()
// do your logic here

);
stopSelf();

;

@Override
public void onDestroy()
this.isRunning = false;


@Override
public int onStartCommand(Intent intent, int flags, int startId)
if (!this.isRunning)
this.isRunning = true;
this.backgroundThread.start();

return START_STICKY;





And to call this class edit ServiceReciever to be like this



 @Override
public void onReceive(Context context, Intent intent)
//call the method here
Intent background = new Intent(context, BackgroundTask.class);
context.startService(background);






share|improve this answer

























  • I need to keep the same service up almost for 20 o 30 minutes, without lossing the state of the webview, so I think the problem is not to start with the alarm manager or not, the real problem is to stay all this time doing a lot of job consuming cpu and ram

    – Pablo Cegarra
    Nov 16 '18 at 19:14












  • for me when i was running tests with short times it never failed even when the app was killed , you can try it and give me feedback i will be able to edit it for you

    – Hossam Hassan
    Nov 16 '18 at 19:28











  • this library is working fine, but only when the app is in foreground, removing the app the broadcast/service is going to be "killed"

    – Pablo Cegarra
    Nov 17 '18 at 17:05












  • I will update my answer with code to run it even in the background

    – Hossam Hassan
    Nov 17 '18 at 17:11












  • Ops! If I call a service then I have the same problem, android services stops my code when the device is idle

    – Pablo Cegarra
    Nov 17 '18 at 17:57










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53299557%2fandroid-foreground-service-slow-if-device-is-idle%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














I have made this library the other day for something similar service in background and foreground



And its working absolutely fine with no problems.



The reason I choose to run it with AlarmManager is that the AlarmManager is a great candidate for scheduling if an application needs to perform a local event + allows an application to schedule tasks that may need to run or repeat beyond the scope of its lifecycle. This allows the application to perform some function even after the application process or all of its Android components have been cleaned up by the system.



UPDATE



Call this method to start the service



 public void call(int Value_in_seconds) 
if (Value_in_seconds == (int) Value_in_seconds)
// Number is integer
Long time = new GregorianCalendar().getTimeInMillis() + Value_in_seconds * 1000;
// create an Intent and set the class which will execute when Alarm triggers, here
// ServiceReciever in the Intent, the onRecieve() method of this class will execute when
// alarm triggers
Intent intentAlarm = new Intent(context, ServiceReciever.class);
// create the object
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
//set the alarm for particular time
alarmManager.set(AlarmManager.RTC_WAKEUP, time, PendingIntent.getBroadcast(context, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
else
Toast.makeText(context, context.getString(R.string.intValue), Toast.LENGTH_SHORT).show();




Create ServiceReciever Class



public class ServiceReciever extends BroadcastReceiver 

@Override
public void onReceive(Context context, Intent intent)
//call the method here





inside your manifest



<application>
<receiver android:name="hossamscott.com.github.backgroundservice.ServiceReciever" android:process=":ff" android:exported="true" android:enabled="true">
</receiver>

<service android:name="hossamscott.com.github.backgroundservice.BackgroundTask"/>

</application>


And thats should be it, tho if you like to run it in Thread
Than you can add the next lines



public class BackgroundTask extends Service 

private boolean isRunning;
private Context context;
private Thread backgroundThread;


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


@Override
public void onCreate()
this.context = this;
this.isRunning = false;
this.backgroundThread = new Thread(myTask);


private Runnable myTask = new Runnable()
public void run()
// Do something here
new Handler(Looper.getMainLooper()).post(new Runnable()
@Override
public void run()
// do your logic here

);
stopSelf();

;

@Override
public void onDestroy()
this.isRunning = false;


@Override
public int onStartCommand(Intent intent, int flags, int startId)
if (!this.isRunning)
this.isRunning = true;
this.backgroundThread.start();

return START_STICKY;





And to call this class edit ServiceReciever to be like this



 @Override
public void onReceive(Context context, Intent intent)
//call the method here
Intent background = new Intent(context, BackgroundTask.class);
context.startService(background);






share|improve this answer

























  • I need to keep the same service up almost for 20 o 30 minutes, without lossing the state of the webview, so I think the problem is not to start with the alarm manager or not, the real problem is to stay all this time doing a lot of job consuming cpu and ram

    – Pablo Cegarra
    Nov 16 '18 at 19:14












  • for me when i was running tests with short times it never failed even when the app was killed , you can try it and give me feedback i will be able to edit it for you

    – Hossam Hassan
    Nov 16 '18 at 19:28











  • this library is working fine, but only when the app is in foreground, removing the app the broadcast/service is going to be "killed"

    – Pablo Cegarra
    Nov 17 '18 at 17:05












  • I will update my answer with code to run it even in the background

    – Hossam Hassan
    Nov 17 '18 at 17:11












  • Ops! If I call a service then I have the same problem, android services stops my code when the device is idle

    – Pablo Cegarra
    Nov 17 '18 at 17:57















0














I have made this library the other day for something similar service in background and foreground



And its working absolutely fine with no problems.



The reason I choose to run it with AlarmManager is that the AlarmManager is a great candidate for scheduling if an application needs to perform a local event + allows an application to schedule tasks that may need to run or repeat beyond the scope of its lifecycle. This allows the application to perform some function even after the application process or all of its Android components have been cleaned up by the system.



UPDATE



Call this method to start the service



 public void call(int Value_in_seconds) 
if (Value_in_seconds == (int) Value_in_seconds)
// Number is integer
Long time = new GregorianCalendar().getTimeInMillis() + Value_in_seconds * 1000;
// create an Intent and set the class which will execute when Alarm triggers, here
// ServiceReciever in the Intent, the onRecieve() method of this class will execute when
// alarm triggers
Intent intentAlarm = new Intent(context, ServiceReciever.class);
// create the object
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
//set the alarm for particular time
alarmManager.set(AlarmManager.RTC_WAKEUP, time, PendingIntent.getBroadcast(context, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
else
Toast.makeText(context, context.getString(R.string.intValue), Toast.LENGTH_SHORT).show();




Create ServiceReciever Class



public class ServiceReciever extends BroadcastReceiver 

@Override
public void onReceive(Context context, Intent intent)
//call the method here





inside your manifest



<application>
<receiver android:name="hossamscott.com.github.backgroundservice.ServiceReciever" android:process=":ff" android:exported="true" android:enabled="true">
</receiver>

<service android:name="hossamscott.com.github.backgroundservice.BackgroundTask"/>

</application>


And thats should be it, tho if you like to run it in Thread
Than you can add the next lines



public class BackgroundTask extends Service 

private boolean isRunning;
private Context context;
private Thread backgroundThread;


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


@Override
public void onCreate()
this.context = this;
this.isRunning = false;
this.backgroundThread = new Thread(myTask);


private Runnable myTask = new Runnable()
public void run()
// Do something here
new Handler(Looper.getMainLooper()).post(new Runnable()
@Override
public void run()
// do your logic here

);
stopSelf();

;

@Override
public void onDestroy()
this.isRunning = false;


@Override
public int onStartCommand(Intent intent, int flags, int startId)
if (!this.isRunning)
this.isRunning = true;
this.backgroundThread.start();

return START_STICKY;





And to call this class edit ServiceReciever to be like this



 @Override
public void onReceive(Context context, Intent intent)
//call the method here
Intent background = new Intent(context, BackgroundTask.class);
context.startService(background);






share|improve this answer

























  • I need to keep the same service up almost for 20 o 30 minutes, without lossing the state of the webview, so I think the problem is not to start with the alarm manager or not, the real problem is to stay all this time doing a lot of job consuming cpu and ram

    – Pablo Cegarra
    Nov 16 '18 at 19:14












  • for me when i was running tests with short times it never failed even when the app was killed , you can try it and give me feedback i will be able to edit it for you

    – Hossam Hassan
    Nov 16 '18 at 19:28











  • this library is working fine, but only when the app is in foreground, removing the app the broadcast/service is going to be "killed"

    – Pablo Cegarra
    Nov 17 '18 at 17:05












  • I will update my answer with code to run it even in the background

    – Hossam Hassan
    Nov 17 '18 at 17:11












  • Ops! If I call a service then I have the same problem, android services stops my code when the device is idle

    – Pablo Cegarra
    Nov 17 '18 at 17:57













0












0








0







I have made this library the other day for something similar service in background and foreground



And its working absolutely fine with no problems.



The reason I choose to run it with AlarmManager is that the AlarmManager is a great candidate for scheduling if an application needs to perform a local event + allows an application to schedule tasks that may need to run or repeat beyond the scope of its lifecycle. This allows the application to perform some function even after the application process or all of its Android components have been cleaned up by the system.



UPDATE



Call this method to start the service



 public void call(int Value_in_seconds) 
if (Value_in_seconds == (int) Value_in_seconds)
// Number is integer
Long time = new GregorianCalendar().getTimeInMillis() + Value_in_seconds * 1000;
// create an Intent and set the class which will execute when Alarm triggers, here
// ServiceReciever in the Intent, the onRecieve() method of this class will execute when
// alarm triggers
Intent intentAlarm = new Intent(context, ServiceReciever.class);
// create the object
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
//set the alarm for particular time
alarmManager.set(AlarmManager.RTC_WAKEUP, time, PendingIntent.getBroadcast(context, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
else
Toast.makeText(context, context.getString(R.string.intValue), Toast.LENGTH_SHORT).show();




Create ServiceReciever Class



public class ServiceReciever extends BroadcastReceiver 

@Override
public void onReceive(Context context, Intent intent)
//call the method here





inside your manifest



<application>
<receiver android:name="hossamscott.com.github.backgroundservice.ServiceReciever" android:process=":ff" android:exported="true" android:enabled="true">
</receiver>

<service android:name="hossamscott.com.github.backgroundservice.BackgroundTask"/>

</application>


And thats should be it, tho if you like to run it in Thread
Than you can add the next lines



public class BackgroundTask extends Service 

private boolean isRunning;
private Context context;
private Thread backgroundThread;


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


@Override
public void onCreate()
this.context = this;
this.isRunning = false;
this.backgroundThread = new Thread(myTask);


private Runnable myTask = new Runnable()
public void run()
// Do something here
new Handler(Looper.getMainLooper()).post(new Runnable()
@Override
public void run()
// do your logic here

);
stopSelf();

;

@Override
public void onDestroy()
this.isRunning = false;


@Override
public int onStartCommand(Intent intent, int flags, int startId)
if (!this.isRunning)
this.isRunning = true;
this.backgroundThread.start();

return START_STICKY;





And to call this class edit ServiceReciever to be like this



 @Override
public void onReceive(Context context, Intent intent)
//call the method here
Intent background = new Intent(context, BackgroundTask.class);
context.startService(background);






share|improve this answer















I have made this library the other day for something similar service in background and foreground



And its working absolutely fine with no problems.



The reason I choose to run it with AlarmManager is that the AlarmManager is a great candidate for scheduling if an application needs to perform a local event + allows an application to schedule tasks that may need to run or repeat beyond the scope of its lifecycle. This allows the application to perform some function even after the application process or all of its Android components have been cleaned up by the system.



UPDATE



Call this method to start the service



 public void call(int Value_in_seconds) 
if (Value_in_seconds == (int) Value_in_seconds)
// Number is integer
Long time = new GregorianCalendar().getTimeInMillis() + Value_in_seconds * 1000;
// create an Intent and set the class which will execute when Alarm triggers, here
// ServiceReciever in the Intent, the onRecieve() method of this class will execute when
// alarm triggers
Intent intentAlarm = new Intent(context, ServiceReciever.class);
// create the object
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
//set the alarm for particular time
alarmManager.set(AlarmManager.RTC_WAKEUP, time, PendingIntent.getBroadcast(context, 1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
else
Toast.makeText(context, context.getString(R.string.intValue), Toast.LENGTH_SHORT).show();




Create ServiceReciever Class



public class ServiceReciever extends BroadcastReceiver 

@Override
public void onReceive(Context context, Intent intent)
//call the method here





inside your manifest



<application>
<receiver android:name="hossamscott.com.github.backgroundservice.ServiceReciever" android:process=":ff" android:exported="true" android:enabled="true">
</receiver>

<service android:name="hossamscott.com.github.backgroundservice.BackgroundTask"/>

</application>


And thats should be it, tho if you like to run it in Thread
Than you can add the next lines



public class BackgroundTask extends Service 

private boolean isRunning;
private Context context;
private Thread backgroundThread;


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


@Override
public void onCreate()
this.context = this;
this.isRunning = false;
this.backgroundThread = new Thread(myTask);


private Runnable myTask = new Runnable()
public void run()
// Do something here
new Handler(Looper.getMainLooper()).post(new Runnable()
@Override
public void run()
// do your logic here

);
stopSelf();

;

@Override
public void onDestroy()
this.isRunning = false;


@Override
public int onStartCommand(Intent intent, int flags, int startId)
if (!this.isRunning)
this.isRunning = true;
this.backgroundThread.start();

return START_STICKY;





And to call this class edit ServiceReciever to be like this



 @Override
public void onReceive(Context context, Intent intent)
//call the method here
Intent background = new Intent(context, BackgroundTask.class);
context.startService(background);







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 17 '18 at 17:23

























answered Nov 16 '18 at 18:27









Hossam HassanHossam Hassan

2971317




2971317












  • I need to keep the same service up almost for 20 o 30 minutes, without lossing the state of the webview, so I think the problem is not to start with the alarm manager or not, the real problem is to stay all this time doing a lot of job consuming cpu and ram

    – Pablo Cegarra
    Nov 16 '18 at 19:14












  • for me when i was running tests with short times it never failed even when the app was killed , you can try it and give me feedback i will be able to edit it for you

    – Hossam Hassan
    Nov 16 '18 at 19:28











  • this library is working fine, but only when the app is in foreground, removing the app the broadcast/service is going to be "killed"

    – Pablo Cegarra
    Nov 17 '18 at 17:05












  • I will update my answer with code to run it even in the background

    – Hossam Hassan
    Nov 17 '18 at 17:11












  • Ops! If I call a service then I have the same problem, android services stops my code when the device is idle

    – Pablo Cegarra
    Nov 17 '18 at 17:57

















  • I need to keep the same service up almost for 20 o 30 minutes, without lossing the state of the webview, so I think the problem is not to start with the alarm manager or not, the real problem is to stay all this time doing a lot of job consuming cpu and ram

    – Pablo Cegarra
    Nov 16 '18 at 19:14












  • for me when i was running tests with short times it never failed even when the app was killed , you can try it and give me feedback i will be able to edit it for you

    – Hossam Hassan
    Nov 16 '18 at 19:28











  • this library is working fine, but only when the app is in foreground, removing the app the broadcast/service is going to be "killed"

    – Pablo Cegarra
    Nov 17 '18 at 17:05












  • I will update my answer with code to run it even in the background

    – Hossam Hassan
    Nov 17 '18 at 17:11












  • Ops! If I call a service then I have the same problem, android services stops my code when the device is idle

    – Pablo Cegarra
    Nov 17 '18 at 17:57
















I need to keep the same service up almost for 20 o 30 minutes, without lossing the state of the webview, so I think the problem is not to start with the alarm manager or not, the real problem is to stay all this time doing a lot of job consuming cpu and ram

– Pablo Cegarra
Nov 16 '18 at 19:14






I need to keep the same service up almost for 20 o 30 minutes, without lossing the state of the webview, so I think the problem is not to start with the alarm manager or not, the real problem is to stay all this time doing a lot of job consuming cpu and ram

– Pablo Cegarra
Nov 16 '18 at 19:14














for me when i was running tests with short times it never failed even when the app was killed , you can try it and give me feedback i will be able to edit it for you

– Hossam Hassan
Nov 16 '18 at 19:28





for me when i was running tests with short times it never failed even when the app was killed , you can try it and give me feedback i will be able to edit it for you

– Hossam Hassan
Nov 16 '18 at 19:28













this library is working fine, but only when the app is in foreground, removing the app the broadcast/service is going to be "killed"

– Pablo Cegarra
Nov 17 '18 at 17:05






this library is working fine, but only when the app is in foreground, removing the app the broadcast/service is going to be "killed"

– Pablo Cegarra
Nov 17 '18 at 17:05














I will update my answer with code to run it even in the background

– Hossam Hassan
Nov 17 '18 at 17:11






I will update my answer with code to run it even in the background

– Hossam Hassan
Nov 17 '18 at 17:11














Ops! If I call a service then I have the same problem, android services stops my code when the device is idle

– Pablo Cegarra
Nov 17 '18 at 17:57





Ops! If I call a service then I have the same problem, android services stops my code when the device is idle

– Pablo Cegarra
Nov 17 '18 at 17:57

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53299557%2fandroid-foreground-service-slow-if-device-is-idle%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Top Tejano songwriter Luis Silva dead of heart attack at 64

ReactJS Fetched API data displays live - need Data displayed static

Evgeni Malkin