Keeping A Background Service Alive On Android
Solution 1:
All you have to do to have a service that is constently alive is:
<!-- BackGroundService Service --><serviceandroid:name="com.settings.BackgroundService"android:enabled="true"android:exported="false"android:process=":my_process" />
2) onStartCommand should return:
return Service.START_STICKY;
and that's all buddy after I Start the service from the main activity it is on for the whole day/
Solution 2:
You need to use a Partial Wakelock with the service. If your service is interactive with the user, you might consider making the service foreground.
This is a working example for a Partial Wakelock:
Use this when service is started:
PowerManagerpm= (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLockcpuWakeLock= pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
cpuWakeLock.acquire();
When the service is stopped, do call cpuWakeLock.release();
imports android.support.v4.content.WakefulBroadcastReceiver which Android Studio is telling me doesn't exist.
You need to import the support library for that.
Solution 3:
To do the trick use JobScheduler and JobService which allow you to execute code periodically.
First create a class that extends JobService, then implement required methods and add your service code/start another service from within the JobService onStartJob() method.
Here's an example for executing a JobService operation periodically:
ComponentNameserviceComponent=newComponentName(context, yourJobService.class);
JobInfo.Builderbuilder=newJobInfo.Builder(0, serviceComponent);
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED);
builder.setRequiresDeviceIdle(false);
builder.setRequiresCharging(false);
builder.setPeriodic(60000); // <<<<---- 60 seconds intervalJobSchedulerjobScheduler= (JobScheduler)context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(builder.build());
You can find more info here: https://developer.android.com/reference/android/app/job/JobService.html
Good luck!
Post a Comment for "Keeping A Background Service Alive On Android"