Android Starting Service at Boot Time , How to restart service class after device Reboot?

158,631

Solution 1

Create a BroadcastReceiver and register it to receive ACTION_BOOT_COMPLETED. You also need RECEIVE_BOOT_COMPLETED permission.

Read: Listening For and Broadcasting Global Messages, and Setting Alarms

Solution 2

Your receiver:

public class MyReceiver extends BroadcastReceiver {   

    @Override
    public void onReceive(Context context, Intent intent) {

     Intent myIntent = new Intent(context, YourService.class);
     context.startService(myIntent);

    }
}

Your AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.broadcast.receiver.example"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true">

        <activity android:name=".BR_Example"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    <!-- Declaring broadcast receiver for BOOT_COMPLETED event. -->
        <receiver android:name=".MyReceiver" android:enabled="true" android:exported="false">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>

    </application>

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

</manifest>

Solution 3

It's possible to register your own application service for starting automatically when the device has been booted. You need this, for example, when you want to receive push events from a http server and want to inform the user as soon a new event occurs. The user doesn't have to start the activity manually before the service get started...

It's quite simple. First give your app the permission RECEIVE_BOOT_COMPLETED. Next you need to register a BroadcastReveiver. We call it BootCompletedIntentReceiver.

Your Manifest.xml should now look like this:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.jjoe64">
 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
 <application>
  <receiver android:name=".BootCompletedIntentReceiver">
   <intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED" />
   </intent-filter>
  </receiver>
  <service android:name=".BackgroundService"/>
 </application>
</manifest>

As the last step you have to implement the Receiver. This receiver just starts your background service.

package com.jjoe64;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import com.jjoe64.BackgroundService;

public class BootCompletedIntentReceiver extends BroadcastReceiver {
 @Override
 public void onReceive(Context context, Intent intent) {
  if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
   Intent pushIntent = new Intent(context, BackgroundService.class);
   context.startService(pushIntent);
  }
 }
}

From http://www.jjoe64.com/2011/06/autostart-service-on-device-boot.html

Solution 4

Most the solutions posted here are missing an important piece: doing it without a wake lock runs the risk of your Service getting killed before it is finished processing. Saw this solution in another thread, answering here as well.

Since WakefulBroadcastReceiver is deprecated in api 26 it is recommended for API Levels below 26

You need to obtain a wake lock . Luckily, the Support library gives us a class to do this:

public class SimpleWakefulReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // This is the Intent to deliver to our service.
        Intent service = new Intent(context, SimpleWakefulService.class);

        // Start the service, keeping the device awake while it is launching.
        Log.i("SimpleWakefulReceiver", "Starting service @ " + SystemClock.elapsedRealtime());
        startWakefulService(context, service);
    }
}

then, in your Service, make sure to release the wake lock:

    @Override
    protected void onHandleIntent(Intent intent) {
        // At this point SimpleWakefulReceiver is still holding a wake lock
        // for us.  We can do whatever we need to here and then tell it that
        // it can release the wakelock.

...
        Log.i("SimpleWakefulReceiver", "Completed service @ " + SystemClock.elapsedRealtime());
        SimpleWakefulReceiver.completeWakefulIntent(intent);
    }

Don't forget to add the WAKE_LOCK permission and register your receiver in the manifest:

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

...

<service android:name=".SimpleWakefulReceiver">
    <intent-filter>
        <action android:name="com.example.SimpleWakefulReceiver"/>
    </intent-filter>
</service>

Solution 5

you should register for BOOT_COMPLETE as well as REBOOT

<receiver android:name=".Services.BootComplete">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED"/>
            <action android:name="android.intent.action.REBOOT"/>
        </intent-filter>
    </receiver> 
Share:
158,631

Related videos on Youtube

harish
Author by

harish

Updated on July 08, 2022

Comments

  • harish
    harish almost 2 years

    I need to start a service at boot time. I searched a lot. They are talking about Broadcastreceiver. As I am new to android development, I didn't get a clear picture about services on Android. Please provide some source code.

    • CommonsWare
      CommonsWare over 13 years
      @user244540: Please do not "start a service at boot time" with the intention of it running forever, unless it is continuously delivering value (e.g., a VOIP client). In those cases, use startForeground() in your service. Otherwise, Android and its users will kill off your service as being a waste of space, and you will get some unpleasant comments in the Android Market. Most situations where you think you want a service to start at boot time, you are better served using AlarmManager so your service can run periodically rather than continuously.
    • stanwise
      stanwise almost 12 years
      @CommonsWare: Good point. However note, that to start periodic runs by AlarmManager after restart, you need to follow very similar steps (the difference being in the contents of onReceive method)
    • chiccodoro
      chiccodoro over 10 years
      @CommonsWare: Very good comment, I stumbled across this question and your hint exactly fits my situation. If it was an answer I would have voted it up :-)
  • dbkoren
    dbkoren almost 11 years
    Same as the above but really simple and fast, use this one if u come by this post.
  • Alex
    Alex over 10 years
    The link to the article is dead but the sample code is all you need anyway, so +1 :)
  • Vladimir Ivanov
    Vladimir Ivanov over 10 years
    Actually, it needs little improve, you must use wakelock in receiver, otherwise there is a little chance your service is not going to start.
  • Joaquin Iurchuk
    Joaquin Iurchuk over 9 years
    The only difference is that this declares the Service on the Manifest, which is correct.
  • Joaquin Iurchuk
    Joaquin Iurchuk over 9 years
    Why the Intent Filter inside the service?
  • SoftEye
    SoftEye about 9 years
    because when the boot completed then the MyService will be called
  • Joaquin Iurchuk
    Joaquin Iurchuk about 9 years
    In that case your service class will extend service and broadcast receiver. Am I right?
  • SoftEye
    SoftEye about 9 years
    The class will extend Service class.
  • Joaquin Iurchuk
    Joaquin Iurchuk about 9 years
    There's something wrong here. The service is supposed to be called from the Broadcast Receiver. But you're saying that your service is the broadcast receiver and after that you tell me that the service class doesn't extend Broadcast Receiver. Thus, it won't receive the Boot Completed Broadcast. What are you overriding when you declare the onReceive method?
  • Marian Paździoch
    Marian Paździoch about 9 years
    what about wake lock? while service is being started the device may decide to go asleep...
  • SoftEye
    SoftEye about 9 years
    Yes you are right the service will be called from the broadcast Receiver, and the receiver will be called at boot time.
  • pathe.kiran
    pathe.kiran almost 9 years
    Do i need to boot my mobile at least once to make this work??
  • pathe.kiran
    pathe.kiran almost 9 years
    Do i need to boot my mobile at least once to start a service??
  • phreakhead
    phreakhead almost 9 years
    @MarianPaździoch is right; you need a wake lock. See my answer below: stackoverflow.com/a/30970167/473201
  • Vladimir Ivanov
    Vladimir Ivanov almost 9 years
    Nope, but you must run the application at least one since android 3.0
  • Tim
    Tim over 8 years
  • Tim
    Tim over 8 years
    It is not only correct to declare your service in the manifest, it is required. Same as with activities
  • Desmond Lua
    Desmond Lua about 8 years
    In the manifest file, SimpleWakefulReceiver is not a service.
  • nick
    nick over 7 years
    Where is the Main Activity!? It is not correct to make app without activities or android.intent.category.LAUNCHER!
  • appsthatmatter
    appsthatmatter over 7 years
    @L'Esperanza for sure, you can have apps that have no visible activities!
  • nick
    nick over 7 years
    @jjoe64, if there are no visible activity receiver doesn't work. And service can only be started by another app.
  • Zarul Izham
    Zarul Izham about 7 years
    @L'Esperanza no you're wrong. App can be started without an activity :)
  • Srihari Karanth
    Srihari Karanth almost 7 years
    Does this work if app is force closed from settings? Will the app still wakeup?
  • samsri
    samsri almost 7 years
    How did this work without the service being declared in the manifest?
  • Prizoff
    Prizoff almost 7 years
    Your latest URL is outdated
  • mrid
    mrid almost 7 years
    for some reason, this isn't working for me. my service isn't starting
  • XMAN
    XMAN over 6 years
    Literature says that 'android.intent.action.REBOOT' can only be used by privileged app/code. What advantage is this otherwise?
  • Amin Pinjari
    Amin Pinjari almost 5 years
    WakefulBroadcastReceiver is deprecated