Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Background worker always fails on android, when the app is closed #25

Closed
WilliamSarkisjan opened this issue Aug 7, 2023 · 15 comments
Closed
Assignees
Labels
bug Something isn't working

Comments

@WilliamSarkisjan
Copy link

In my background.js I have one simple event listener:

addEventListener("myCustomEvent", (details) => {
  console.log("launched listener");

  let scheduleDate = new Date();

  CapacitorNotifications.schedule([
    {
      id: 1,
      title: "Enterprise Background Runner",
      body: "Received silent push notification",
      scheduleAt: scheduleDate,
    },
  ]);

  console.log(scheduleDate);

  details.completed();
});

and have my capacitor.config.ts defined as follows:

		"BackgroundRunner": {
			"label": "com.williegg.togetherminds.task",
			"src": "background.js",
			"event": "myCustomEvent",
			"repeat": true,
			"interval": 16,
			"autoStart": true
		}

When I open my app, and then navigate back to my phone home screen (with the app still being open in the background), the background worker always finishes succesfully, and the event listener I have defined is fired/executed correctly.

However, when I completely close my app (so my app itself is not running in the background), my background worker always fails. The worker does fire at the interval I have set, however it never actually executes my eventlistener (since the console.log I put at the beginning of the function never gets executed), and instead the android studio console says that the worker failed.

Is there something I am missing or is this a bug with the plugin?

@peitschie
Copy link

@WilliamSarkisjan how are you closing the app?

What happens if you kill the app via adb: adb shell am kill <package id>?

@WilliamSarkisjan
Copy link
Author

@peitschie I don't do anything special when closing it (I don't force kill it or something). I just close off the app from the recently open apps.

As for the adb command, where/how do I run that?

@peitschie
Copy link

I just close off the app from the recently

On some phones, this actually terminates all running processes, even background tasks. What happens if you relax the battery optimizations / task launching permissions for your app? See https://dontkillmyapp.com/ for good tips on how to do this for each device.

As for the adb command, where/how do I run that?

Sorry, it's a lot to slog through for a simple trial, but best place to find this is with Android docs: https://developer.android.com/tools/adb#directingcommands

But, if you're trying to get background tasks going, chances are you'll need to get pretty familiar with how some of the Android native stuff works as there's quite a few gotchyas there.

(disclaimer: I'm not affiliated with the Ionic team or similar... I'm just an old-hand at Android background processing general)

@WilliamSarkisjan
Copy link
Author

@peitschie Thank you for the quick replies I appreciate it!

I had already tried turning off all the battery optimization stuff and it didn't change anything unfortunately. The thing is that in the android studio logcat I can see that the worker process actually does get triggered, but it fails always fails.

I will definitely look into the adb command and see if that will give me more insight. Thanks again :)

@WilliamSarkisjan
Copy link
Author

WilliamSarkisjan commented Aug 7, 2023

As extra information, these are the logs from android studio logcat. As you can see at 11:17:28 and 11:34:52 the "WorkerWrapper" background tasks actually get scheduled, but they fail immediately. However if I leave my app on in the background they are succesfull....

2023-08-07 10:56:08.156  1366-1859  WindowManager           system_server                        E  win=Window{3f8b7a7 u0 com.williegg.togetherminds/com.williegg.togetherminds.MainActivity} destroySurfaces: appStopped=true cleanupOnResume=false win.mWindowRemovalAllowed=false win.mRemoveOnExit=false win.mViewVisibility=8 caller=com.android.server.wm.ActivityRecord.destroySurfaces:6539 com.android.server.wm.ActivityRecord.destroySurfaces:6520 com.android.server.wm.ActivityRecord.notifyAppStopped:6584 com.android.server.wm.ActivityRecord.activityStopped:7172 com.android.server.wm.ActivityClientController.activityStopped:258 android.app.IActivityClientController$Stub.onTransact:613 com.android.server.wm.ActivityClientController.onTransact:136 
2023-08-07 11:17:28.728 22911-22911 g.togetherminds         com.williegg.togetherminds           I  Using CollectorTypeCC GC.
2023-08-07 11:17:28.731 22911-22911 g.togetherminds         com.williegg.togetherminds           E  Not starting debugger since process cannot load the jdwp agent.
2023-08-07 11:17:28.736 22911-22911 ActivityThread          com.williegg.togetherminds           D  setConscryptValidator
2023-08-07 11:17:28.736 22911-22911 ActivityThread          com.williegg.togetherminds           D  setConscryptValidator - put
2023-08-07 11:17:28.743 22911-22911 Compatibil...geReporter com.williegg.togetherminds           D  Compat change id reported: 171979766; UID 10477; state: ENABLED
2023-08-07 11:17:28.748 22911-22911 nativeloader            com.williegg.togetherminds           D  Configuring classloader-namespace for other apk /data/app/~~NVixIeML_T_Xkszo84S5qg==/com.williegg.togetherminds-8Sz6MxdjMRkaPAo7QvtzAQ==/base.apk. target_sdk_version=33, uses_libraries=, library_path=/data/app/~~NVixIeML_T_Xkszo84S5qg==/com.williegg.togetherminds-8Sz6MxdjMRkaPAo7QvtzAQ==/lib/arm64:/data/app/~~NVixIeML_T_Xkszo84S5qg==/com.williegg.togetherminds-8Sz6MxdjMRkaPAo7QvtzAQ==/base.apk!/lib/arm64-v8a, permitted_path=/data:/mnt/expand:/data/user/0/com.williegg.togetherminds
2023-08-07 11:17:28.755 22911-22911 GraphicsEnvironment     com.williegg.togetherminds           V  ANGLE Developer option for 'com.williegg.togetherminds' set to: 'default'
2023-08-07 11:17:28.756 22911-22911 GraphicsEnvironment     com.williegg.togetherminds           V  ANGLE GameManagerService for com.williegg.togetherminds: false
2023-08-07 11:17:28.756 22911-22911 GraphicsEnvironment     com.williegg.togetherminds           V  App is not on the allowlist for updatable production driver.
2023-08-07 11:17:28.757 22911-22911 NetworkSecurityConfig   com.williegg.togetherminds           D  No Network Security Config specified, using platform default
2023-08-07 11:17:28.759 22911-22911 NetworkSecurityConfig   com.williegg.togetherminds           D  No Network Security Config specified, using platform default
2023-08-07 11:17:28.764 22911-22911 Compatibil...geReporter com.williegg.togetherminds           D  Compat change id reported: 183155436; UID 10477; state: ENABLED
2023-08-07 11:17:28.767 22911-22911 FirebaseApp             com.williegg.togetherminds           I  Device unlocked: initializing all Firebase APIs for app [DEFAULT]
2023-08-07 11:17:28.772 22911-22911 FirebaseInitProvider    com.williegg.togetherminds           I  FirebaseApp initialization successful
2023-08-07 11:17:28.776 22911-22911 WM-WrkMgrInitializer    com.williegg.togetherminds           D  Initializing WorkManager with default configuration.
2023-08-07 11:17:28.824 22911-22939 Compatibil...geReporter com.williegg.togetherminds           D  Compat change id reported: 160794467; UID 10477; state: ENABLED
2023-08-07 11:17:28.911 22911-22944 WM-WorkerWrapper        com.williegg.togetherminds           I  Worker result FAILURE for Work [ id=37d97df2-b0d3-4254-b33f-4c2e4c8c29be, tags={ io.ionic.backgroundrunner.plugin.RunnerWorker, com.williegg.togetherminds.task } ]
2023-08-07 11:17:28.943 22911-22944 Compatibil...geReporter com.williegg.togetherminds           D  Compat change id reported: 194532703; UID 10477; state: ENABLED
2023-08-07 11:17:33.879 22911-23032 ProfileInstaller        com.williegg.togetherminds           D  Skipping profile installation for com.williegg.togetherminds
2023-08-07 11:34:52.520 22911-22939 WM-WorkerWrapper        com.williegg.togetherminds           I  Worker result FAILURE for Work [ id=37d97df2-b0d3-4254-b33f-4c2e4c8c29be, tags={ io.ionic.backgroundrunner.plugin.RunnerWorker, com.williegg.togetherminds.task } ]

I noticed that during succesfull runs, when the app is open in the background, [Runner Co...inds.task] is executed, which doesn't happen when the app is closed

2023-08-07 11:50:52.582 22911-30060 [Runner Co...inds.task] com.williegg.togetherminds           I  launched listener
2023-08-07 11:50:52.603 22911-30060 [Runner Co...inds.task] com.williegg.togetherminds           I  Mon Aug 07 2023 11:50:52 GMT+0200
2023-08-07 11:50:53.110 22911-22939 WM-WorkerWrapper        com.williegg.togetherminds           I  Worker result SUCCESS for Work [ id=37d97df2-b0d3-4254-b33f-4c2e4c8c29be, tags={ io.ionic.backgroundrunner.plugin.RunnerWorker, com.williegg.togetherminds.task } ]

@theproducer theproducer self-assigned this Aug 7, 2023
@theproducer
Copy link
Collaborator

Hello @WilliamSarkisjan!

What version of Android is this, and what device manufacturer?

You mentioned it works in the foreground - is the notification successfully displayed?

@WilliamSarkisjan
Copy link
Author

WilliamSarkisjan commented Aug 7, 2023

@theproducer Hi!

I have the Samsung Galaxy S22 ultra (SM-S908B) with android version 13.
Indeed when the app is open in the foreground (or when I navigate back from the app but i haven't closed the app completely) the notification/eventhandler gets called correctly, and the worker process returns "SUCCESFULL".

I have tried everything from giving unrestricted access to battery resources, to making the interval time of the background process longer, but nothing works.

When i dispatch events from the app itself it works perfectly too

@theproducer
Copy link
Collaborator

Since its Android 13, did you configure permissions correctly?
https://capacitorjs.com/docs/apis/background-runner#local-notifications

Additionally, try wrapping your code in a try / catch (with the catch containing a console.error with a string based message indicating a problem) to see if it's throwing for some reason. Currently, any uncaught errors thrown while the app is in the background will not be logged.

@WilliamSarkisjan
Copy link
Author

@theproducer I indeed have the 'schedule exact alarm' in my androidmanifest, and when the app is in the foreground the notification actually gets delivered. I just added the console.error with try catch, but no error is being thrown as I expected..

The only time the worker ever fails is when the app is closed

@theproducer theproducer added the bug Something isn't working label Aug 7, 2023
@WilliamSarkisjan
Copy link
Author

Is there any update on this?

@zarko-tg
Copy link

I can observe on an Android emulator that a closed app (yes, Google calls it closing) leads to the background runner not working, ex.

WM-WorkerWrapper: Worker result FAILURE for Work [ id=bda753d7-43f5-4b12-a3fc-8629e2d988e3, tags={ io.ionic.backgroundrunner.plugin.RunnerWorker, app.foo.bar } ]

Is this a plugin bug/missing feature, or it's simply not possible for a background runner to work while the app is closed/killed?
Since it isn't that uncommon for end-users to "close" their apps by swipe-up.

@theproducer
Copy link
Collaborator

@zarko-tg Interesting, I looked a bit more into this based on that failure log, and it looks like you are right, "forced closing" an app will also kill any scheduled work manager tasks. It also appears that certain vendors modify the assumed behavior even more drastically:
https://issuetracker.google.com/issues/113676489

We have a call out to potential Android device limitations here, but we may have to expand that section with more detail.
Apparently Samsung is the most severe offender in getting background tasks to work properly:
https://dontkillmyapp.com/samsung

Im not going to close this just yet, as I have several Samsung devices on the way I want to test with. This plugin was initially tested with a Samsung S21 running Android 13, so I will go back and confirm that it still works (and document what device settings were set), and see if I can replicate that on the other devices.

But in the end there may not be anything we can do about this, especially if its true that Samsung is killing even foreground services. If WorkManager's API will not work, it's likely that the other possible APIs are limited as well.

@zarko-tg
Copy link

@theproducer So, I'd even take a step back from mentioning other vendors, as the bug/limitation is apparent on stock/vanilla Android emulator. In my case I tested on Android 13.
I don't know if anything can be done about this within plugin code/logic, but I think it drastically limits the its usefulness.

@WilliamSarkisjan
Copy link
Author

@theproducer are there any updates on this

@theproducer
Copy link
Collaborator

@zarko-tg @WilliamSarkisjan
I've just released version 1.1.0 that addresses various issues on the Android side with Background Runner.

Additionally, I've put up a Background Runner Test App that uses BR in some sample scenarios. After turning off each manufacturers battery optimizations, the app has worked well in testing for months thus far, and updates were reliability performed even across device updates and restarts. And at least on a Samsung S21 - even after "closing" an app.

If you continue to run into Work Manager failures, see if you can reproduce those issues with the test app and create new issues here, with the device manufacturer and model and Android version.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

4 participants