-2

How can I write a service, which starts automatically when the device boots? For example: when I start my phone, I get my new WhatsApp Messages, without opening WhatsApp before.

Matt Way
  • 32,319
  • 10
  • 79
  • 85
Erik
  • 11

2 Answers2

1

Two addition to Himanshu's answer:

  • A boot-listening app must not be installed on the sdcard. Remember that the device boot may be completed before the sdcard is even mounted resulting in your app's boot listener not being activated

  • The boot-listener will not be activated until the user will activate your app for the first time. Starting 4.2 (not sure here) android prevents all services & listeners declared by a newly installed app from being activated until it is explicitly activated by the user.

Explicitly activated as in user clicking the homescreen icon.

Gilad Haimov
  • 5,767
  • 2
  • 26
  • 30
0

You can use this to make it working:

Your manifest file:

<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>

Add this class BootCompletedIntentReceiver.java

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);
        }
    }
}

this will make it auto start your service after boot of device

Xaver Kapeller
  • 49,491
  • 11
  • 98
  • 86
Himanshu Agarwal
  • 4,623
  • 5
  • 35
  • 49
  • Why are you hardcoding the `Intent` in the `BroadcastReceiver`? Why don't you use the corresponding constant `Intent.ACTION_BOOT_COMPLETED`? Also indent you code with 4 spaces, not one... I already fixed your formatting this time. – Xaver Kapeller Jul 19 '14 at 14:28