Can't receive BOOT_COMPLETED action with receiver

195 Views Asked by At

I'm working on Android application, and I need to implement BootCompletedReceiver to restore my Alarm Manager / Work Manager state from previous boot. However, I am not able to receive the BOOT_COMPLETED signal, and in Logcat I keep to see

Background execution not allowed: receiving Intent { act=android.intent.action.BOOT_COMPLETED flg=0x400010 } to com.example.myapplication/.BootCompletedReceiver

I've read other questions about this topic, but nothing seems to work for me. Also, I'm not even doing anything in a background

<receiver
            android:name=".BootCompletedReceiver"
            android:enabled="true"
            android:exported="true"
            android:label="boot_completed_receiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
                <action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
                <action android:name="android.intent.action.BOOT" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </receiver>
public class BootCompletedReceiver extends BroadcastReceiver {
    private static String TAG = "BootCompletedReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
//            Intent i = new Intent(context, DisplayMessageActivity.class);
//            context.startActivity(i);
            Intent i = new Intent(context.getApplicationContext(), BootService.class);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(i);
            } else {
                context.startService(i);
            }
        }
    }
}
public class BootService extends Service {

    public static String TAG = "BootService";
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Notification n = new NotificationCompat.Builder(this, "test_channel_id")
                .setContentTitle("title")
                .setContentText("text")
                .build();
        startForeground(100, n);
        Log.i(TAG, "created");
        Intent i = new Intent(this.getApplicationContext(), DisplayMessageActivity.class);
        startActivity(i);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "start command");
        Toast.makeText(this, "start command", Toast.LENGTH_LONG).show();
        return super.onStartCommand(intent, flags, startId);
    }
}
0

There are 0 best solutions below