Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

444
Views
Keep a service running all the time even after a reboot

I have implelemented the START_STICKY command but the service is killed after a few hours. What I want to do is keep a service running always in the background and restart even when the device is rebooted. Can I restart the service in the onDestroy method like this? or is there a more convenient approach to it?

 @Override
public void onDestroy() {

   Stop();

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

    Intent i= new Intent(getApplicationContext(), MyService.class);
    startService(i);


}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

For ensuring that your service is running even after some hours of starting it, then you will have to use AlarmManager which will run recurringly for a specified periodicity even if the app is killed. What will you do is register a PendingIntent for the AlarmManager to fire which will be received by a BroadcastReceiver and in the BroadcastReceiver you will check that if your Service is running or not. If running, do nothing and if not then start the service.

What I want to do is keep a service running always in the background and restart even when the device is rebooted.

In order to do this you will have to give this permission in the manifest:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

and then you will have to make a custom BroadcastReceiver which will check for an intent to be fired which is Action.BOOT_COMPLETED.

You should declare your BroadcastReceiver to catch the above mentioned intent in the Android Manifest like this:

<receiver android:name="com.example.MyBroadcastReceiver">  
  <intent-filter>  
    <action android:name="android.intent.action.BOOT_COMPLETED" />  
  </intent-filter>  
</receiver>

Now either you can initialise your AlarmManager in BroadcastReceiver class or you can write the code to start the service straightaway.

Info on AlarmManager can be found here.

Disclaimer: Starting from Android O, Google will stop supporting Unbound Background Service and calling startService() will become Illegal(Android will throw IllegalStateException) when calling this function.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!