ArghadipDasCEO
ArghadipDasCEO

Reputation: 187

Android - Start a service on boot not working

In my app, I'm trying to start a service on phone boot. But it's not responding at all.

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

In the manifest, I did this.

<receiver android:name=".ServiceStarter" android:enabled="true">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" tools:ignore="BatteryLife" />
    </intent-filter>
</receiver>

Inside the service AppServices.class

onCreate {
Toast.makeText(getAppContext(),
"Phone booted", Toast.length_long).show(); //just for test
    andMyOtherCodeAsWell();
    }

But it's not working at all, can anyone help me with the issue?

SOLVE working after 15 secs of the boot even the app is not running in the background(manually cleared by user).

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

Upvotes: 0

Views: 1216

Answers (2)

Dmitry
Dmitry

Reputation: 2556

You can try to put a breakpoint inside the BroadcaseReceiver and then send BOOT_COMPLETED broadcast via adb with the following command:

adb shell am broadcast -a android.intent.action.BOOT_COMPLETED -p com.example.package

(Don't forget to change com.example.package to your package name).

This way you can check and see if your broadcast receiver is getting called.

Upvotes: 2

Mark
Mark

Reputation: 9929

Check your API version. Oreo behaviour changes - If you attempt to call startService() when your application is not in the foreground then an IllegalStateException will be thrown.

Docs :

Context.startForegroundService() method starts a foreground service. The system allows apps to call Context.startForegroundService() even while the app is in the background. However, the app must call that service's startForeground() method within five seconds after the service is created.

so call:

context.startForegroundService() in your BroadcastReceiver and promote your service to a foreground service within 5 seconds of it starting by showing a notification i.e.: startForeground(NOTIFICATION_ID, notification);

Also make sure you have the correct permissions:

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

Upvotes: 3

Related Questions