I want to start the service when the device boots, what should I do?

Asked 2 years ago, Updated 2 years ago, 72 views

I made the code to start the service when the Android device was booted. It doesn't move properly. Did I make a mistake?

<receiver
    android:name=".StartServiceAtBootReceiver"
    android:enabled="true"
    android:exported="false"
    android:label="StartServiceAtBootReceiver" >
    <intent-filter>
        <action android:name="android.intent.action._BOOT_COMPLETED" />
    </intent-filter>
</receiver>

<service
    android:name="com.test.RunService"
    android:enabled="true" />
public void onReceive(Context context, Intent intent) {
    if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
        Intent serviceLauncher = new Intent(context, RunService.class);
        context.startService(serviceLauncher);
        Log.v("TEST", "Service loaded at start");
    }
}

android service broadcastreceiver

2022-09-22 22:27

1 Answers

First, go to the Android manifest file **** You have to add this.

And then you go to the element of the application

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

Please add this.

Go to the broadcast receiver and

package com.example;

public class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent startServiceIntent = new Intent(context, MyService.class);
        context.startService(startServiceIntent);
    }
}

Please do it like this.


2022-09-22 22:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.