Search code examples
javaandroidservicebroadcastreceiverautostart

Android 7.0 Autostart Service doesnt Work


I am currently making a app that starts a http server service on boot. It worked at first but it randomly stopped working.

This is my AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:installLocation="internalOnly">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
        android:maxSdkVersion="32" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
        android:maxSdkVersion="32" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.TestApp"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:label="@string/app_name"
            android:theme="@style/Theme.TestApp">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name="me.rapierxbox.TestApp.BootReceiver"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>
        <service android:name=".HttpServer" />
    </application>
</manifest>

and this is my BootReciver:

public class BootReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("autostart","autostart recived");
        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
            Intent serviceIntent = new Intent(context, HttpServer.class);
            context.startService(serviceIntent);
        }
    }
}

Even when I broadcast the Intend myself using ./adb shell am broadcast -a android.intent.action.BOOT_COMPLETED I get no Logcat logs and neither the service starts.


Solution

  • You'd have to use androidx.legacy.content.WakefulBroadcastReceiver (meanwhile deprecated).

    // https://mvnrepository.com/artifact/androidx.legacy/legacy-support-core-utils
    runtimeOnly "androidx.legacy:legacy-support-core-utils:1.0.0"