React native android targeted android 31 send headless task

Viewed 21

I am new in react native development. I have an app where it is depended on android SDK 31. For some reason I want to send headless task when my app is killed. When I run my code on Android 10 it is running as well. When I try to run the same code on Android 12 and Android 11 it is retrieve an error like that:

android.app.ForegroundServiceStartNotAllowedException: startForegroundService() not allowed due to mAllowStartForeground false:

my code for calling the service is:

Intent headlessService = new Intent(mContext, HeadlessTask.class);
     
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.O) 
{
    mContext.startService(headlessService);

}else{

    mContext.startForegroundService(headlessService);
}

   HeadlessJsTaskService.acquireWakeLockNow(mContext);

my service class is:

public class HeadlessTask extends HeadlessJsTaskService {
    public HeadlessTask() {
    }



    @Nullable
    @Override
    protected HeadlessJsTaskConfig getTaskConfig(Intent intent) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createChannel();
            String title = "";
            String text = "";
            int iconResource = -1;

            Notification notification = new NotificationCompat.Builder(getApplicationContext(), "channel")
                    .setContentTitle(title)
                    .setContentText(text)
                    .setTimeoutAfter(1)
                    .setOngoing(true)
                    .build();
            startForeground(1, notification);
        }


        Bundle extras = intent.getExtras();

        if(extras != null){
            Log.i("beacon.test.app","Extras is not null");
            return new HeadlessJsTaskConfig(
                    "myHeadlessCallback",
                    Arguments.fromBundle(extras),
                    5000, // timeout for the task
                    true // optional: defines whether or not  the task is allowed in foreground. Default is false

            );


        }
      
        return null;

    }

Please tell me if any other way exists to wake up my application without sending headless task.

0 Answers
Related