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

Capacitor 4 after 5 minutes stop working #89

Closed
ghimarcos opened this issue Feb 2, 2023 · 63 comments
Closed

Capacitor 4 after 5 minutes stop working #89

ghimarcos opened this issue Feb 2, 2023 · 63 comments

Comments

@ghimarcos
Copy link

Describe the bug

I have an application that was previously on Capacitor version 3.6.0, and it worked perfectly. So we need to update Capacitor to version 4.6.1 and now it always stops working after 5 minutes in while the application is in Background.

To Reproduce

create an application with the following libs:

"@capacitor-community/background-geolocation": "1.2.7",
"@capacitor/android": "4.6.1",
"@capacitor/ios": "4.6.1",
"@capacitor/core": "4.6.1",
"@capacitor/app": "4.1.1",

Remembering that the same code with these lib versions here work perfectly sending POST for more than 5 minutes:

"@capacitor-community/background-geolocation": "1.2.7",
"@capacitor/android": "3.5.1",
"@capacitor/ios": "3.6.0",
"@capacitor/core": "3.6.0",
"@capacitor/app": "1.1.1",
@jamesdiacono
Copy link
Contributor

jamesdiacono commented Feb 2, 2023

Are you using the native HTTP plugin to send your POST requests? See #14 (comment).

@ghimarcos
Copy link
Author

Yes, in both versions (@capacitor 3.6.0 and @capacitor 4.6.1 ), I used native requests from CapacitorHttp, example:

if (window.navigator.onLine) {
const doPost = async () => {
const options = {
url: 'https://myApiUrl',
headers: { 'Authorization': Bearer ${localStorage.getItem('token')}, 'Content-Type': 'application/json' },
data: { trackingCoords: this.trackingCoords },
};
const response: HttpResponse = await Http.post(options);
};
doPost();
}

@ghimarcos ghimarcos closed this as not planned Won't fix, can't repro, duplicate, stale Feb 2, 2023
@ghimarcos ghimarcos reopened this Feb 2, 2023
@jamesdiacono
Copy link
Contributor

Can you reproduce this using the app in the example/ directory?

@ghimarcos
Copy link
Author

I believe so, but only tomorrow, then I'll let you know

@ghimarcos
Copy link
Author

In app from the example/ directory when i generated apk by android studio, it worked correctly in the background for 5 minutes, but then it stopped, I didn't even change the code, could it be that something was missing?

@Samy-F
Copy link

Samy-F commented Feb 3, 2023

I got the same problem. It was working perfectly before I updated to capacitor v4 and it stopped working. Right now it stops after 5 minutes. And yes I am also using HTTP to make requests. Anyone that knows a fix?

@diachedelic
Copy link
Collaborator

Is this affecting iOS, or just Android?

@Samy-F
Copy link

Samy-F commented Feb 3, 2023 via email

@diachedelic
Copy link
Collaborator

Were you using the same version of this plugin for both Capacitor v3 and Capacitor v4? I just want to be sure that it's not a bug I introduced recently.

@Samy-F
Copy link

Samy-F commented Feb 3, 2023 via email

@diachedelic
Copy link
Collaborator

Try setting some breakpoints around

. We must determine whether the issue is with the location provider, or communication with the WebView.

@Samy-F
Copy link

Samy-F commented Feb 4, 2023 via email

@ghimarcos
Copy link
Author

Try setting some breakpoints around

. We must determine whether the issue is with the location provider, or communication with the WebView.

I did this in the example, and from what I noticed, it continues to capture the values, but after 5 minutes it stops sending to the application but continues capturing, if we open the app again, leaving to the background, it sends everything that it captured all at once.

https://drive.google.com/file/d/1XOIMpzMi_0tC_Tawal90O0hAZ9iDBTqI/view?usp=share_link
https://drive.google.com/file/d/11Was8pK6cmcHQh8Xl60QWmgsgx_DK3VU/view?usp=share_link
https://drive.google.com/file/d/1dvS0uXE1L15nigOA6bMDkzZTfT1eRUt8/view?usp=share_link

@diachedelic
Copy link
Collaborator

It seems that the operating system is suspending execution of the WebView. Have you ensured battery optimisation is turned off? See https://dontkillmyapp.com/. It seems strange that upgrading to Capacitor 4 would cause this.

@Samy-F
Copy link

Samy-F commented Feb 6, 2023 via email

@ghimarcos
Copy link
Author

I resolved my problem, it was probably a structural problem, i removed all my code and did it based on the example, some imports changed too, here's how the code made in typescript was in case anyone needs it.

` async addWatcher(background: boolean): Promise {
try {
let id: number;

  const theConfig = Object.assign(
    { stale: true },
    background
      ? {
        backgroundTitle: 'Location you',
        backgroundMessage: 'getting your location.',
      }
      : {
        distanceFilter: 0,
      }
  );

  // eslint-disable-next-line prefer-const
  id = await BackgroundGeolocation.addWatcher(theConfig, function callback(
    location: any,
    error: any
  ): void {
    if (error) {
      if (
        error.code === 'NOT_AUTHORIZED' &&
        window.confirm(
       'This app needs your location, ' +
                'but does not have permission.\n\n' +
                'Open settings now?'
        )
      ) {
        BackgroundGeolocation.openSettings();
      }
      return this.logError(error);
    }

    return console.log('getting', location, 'id :', id);
  });

  console.log('your logic...', id);

} catch (error) {
  console.log(error);
}

}`

@diachedelic
Copy link
Collaborator

I'm not sure that will have resolved your problem. Above your comment there is a reference to a bug report for Capacitor 4, which makes it look like we need some kind of workaround like this to prevent the WebView going to sleep in the background. @Samy-F , do you want to see if you can implement this fix?

@ghimarcos
Copy link
Author

I believe it's not a problem with the background-geolocation plugin, because I'm managing to send Post now normally for as long as I want, and I'm on the latest version of both the capacitor and the geolocation plugin, but I admit that I don't know what the problem really was, I simply deleted everything I had and redid everything again.

@diachedelic
Copy link
Collaborator

OK, I'm glad you got it working. I will leave this issue open because it seems others are having the same problem.

@darwinmanchola
Copy link

Hi,
I have the same problem my appp work fine in background for 5 ~ 10 minutes and then stop de sent locations, but when open again app star work fine.

sorry by my english

@diachedelic
Copy link
Collaborator

Can you replace the handleOnPause method in BackgroundGeolocation.java with the following, and see if that solves the problem?

    @Override
    protected void handleOnPause() {
        if (service != null) {
            service.onActivityStopped();
            new Thread(() -> {
                try {
                    Thread.sleep(1000);
                    this.bridge.getWebView().dispatchWindowVisibilityChanged(View.VISIBLE);
                } catch (Exception ignore) {}
            }).start();
        }
        stoppedWithoutPermissions = !hasRequiredPermissions();
        super.handleOnPause();
    }

@guizmo51
Copy link

guizmo51 commented Feb 24, 2023

Thanks for all your work !
Do you if adding Capacitor Permissions (using annotation per example) can help about background ? I have my own plugin about beacons scanning in background and my device and others where the following permissions were requested hadn't issue about background. I had a try with ten's of users with several device (without the part about the permissions) and they got issues about background location.

I suggest to add the following permissions :

  • android.Manifest.permission.ACCESS_BACKGROUND_LOCATION
  • android.Manifest.permission.FOREGROUND_SERVICE
  • android.Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS

EDIT : ok, I add an issue (no service triggered and no notificatio, using Capacitor 4), now when I add ACCESS_BACKGROUND_LOCATION the notification is OK. I will try the background behavior using this notification.

If you want I can create a PR !
thanks again

@diachedelic
Copy link
Collaborator

That is interesting, but I don't see how can be a permissions problem. The locations are being recorded in the background, but they are only reported to the WebView when the app comes to the foreground again.

Also, on Android, we do not technically record locations in the "background" (see #58 (comment)), so the ACCESS_BACKGROUND_LOCATION should not be necessary.

The FOREGROUND_SERVICE permission is already requested in the plugin's AndroidManifest.xml. I wonder if the REQUEST_IGNORE_BATTERY_OPTIMIZATIONS has something to do with it - but from my understanding, that is just a convenient way to disable battery optimizations, which can be done via the settings anytime).

using annotation per example

Which example is this?

ok, I add an issue (no service triggered and no notificatio, using Capacitor 4)

Can you please link to this issue?

Are you using this plugin, a different plugin, or both?

@ivinantony
Copy link

same issue for me in android pixel 5

@ivinantony
Copy link

Try setting some breakpoints around

. We must determine whether the issue is with the location provider, or communication with the WebView.

I did this in the example, and from what I noticed, it continues to capture the values, but after 5 minutes it stops sending to the application but continues capturing, if we open the app again, leaving to the background, it sends everything that it captured all at once.

https://drive.google.com/file/d/1XOIMpzMi_0tC_Tawal90O0hAZ9iDBTqI/view?usp=share_link https://drive.google.com/file/d/11Was8pK6cmcHQh8Xl60QWmgsgx_DK3VU/view?usp=share_link https://drive.google.com/file/d/1dvS0uXE1L15nigOA6bMDkzZTfT1eRUt8/view?usp=share_link

same happens for me @ghimarcos how you fixed it?

@diachedelic
Copy link
Collaborator

Please test that this is fixed in v1.2.12.

@diachedelic
Copy link
Collaborator

Thank you @alexandermccormick for getting to the bottom of this. I have reverted the WebView hack as of v1.2.13. Ensure that background watchers are created whilst the app is in the foreground, or pin the plugin to v1.2.12 if you really want to rely on the hack.

@vdt2210
Copy link

vdt2210 commented Apr 13, 2023

Hi everyone. I have this issue on Nokia Android 11. I have modified the handleOnPause() and it's worked fine. Is there another way to fix it
I am using "@capacitor-community/background-geolocation": "^1.2.13"

@diachedelic
Copy link
Collaborator

@taivo-digiex Ensure you add any background watchers while the app is still in the foreground.

@vdt2210
Copy link

vdt2210 commented Apr 13, 2023

@taivo-digiex Ensure you add any background watchers while the app is still in the foreground.

Yes, I have. I'm using your example code and it working in background for about 5m before stop

@diachedelic
Copy link
Collaborator

Is your app sending each location in an HTTP request? Can you reproduce the problem using the demo app in the example/ directory of this repository?

@vdt2210
Copy link

vdt2210 commented Apr 13, 2023

Is your app sending each location in an HTTP request? Can you reproduce the problem using the demo app in the example/ directory of this repository?

My app just received location's object and not sending to any database. Sorry if I misunderstand your first question

Is the /example is native app? If that so I don't know how to reproduce the problem in native app. My app is using ionic + angular

@alexandermccormick
Copy link

@taivo-digiex The example/ isn't any more or less "native" than using Ionic + Angular. Ionic is more of a component library, so the example/ only utilizes Capacitor. You will still use the same commands you do when working with an Ionic project, but instead of calling ionic cap [command] you will call capacitor directly with npx cap [command]. The example/ is more plain, as it does not use a web framework but instead simply uses one index.html file and one main.js. You'll find these located in the www directory inside example/.

By lightly modifying the example/ to better match your use case, it will help provide a more clear picture of what might be going on, either with the plugin or your specific architecture.

@diachedelic
Copy link
Collaborator

@taivo-digiex Does the notification remain after 5 minutes, or does it disappear?

@vdt2210
Copy link

vdt2210 commented Apr 14, 2023

@taivo-digiex The example/ isn't any more or less "native" than using Ionic + Angular. Ionic is more of a component library, so the example/ only utilizes Capacitor. You will still use the same commands you do when working with an Ionic project, but instead of calling ionic cap [command] you will call capacitor directly with npx cap [command]. The example/ is more plain, as it does not use a web framework but instead simply uses one index.html file and one main.js. You'll find these located in the www directory inside example/.

By lightly modifying the example/ to better match your use case, it will help provide a more clear picture of what might be going on, either with the plugin or your specific architecture.

Thanks @alexandermccormick. I will try it

@vdt2210
Copy link

vdt2210 commented Apr 14, 2023

@taivo-digiex Does the notification remain after 5 minutes, or does it disappear?

Its still appear with location icon on status bar.

Btw, I have a case when I modified handleOnPause() I had to add the background location permission. If not the app will stop all

@diachedelic
Copy link
Collaborator

When your application receives a location update, what does it do with it? Does it save it to disk? Display it on the screen in some way? How do you know exactly that it is stopping after 5 minutes?

@vdt2210
Copy link

vdt2210 commented Apr 14, 2023

@diachedelic my app is getting location to show on screen only. I have used console.log(new Date)/count i++ to know when it stop on Android studio terminal

@diachedelic
Copy link
Collaborator

OK. Please try to reproduce your problem using the app in example/. When you add watchers, each location update is logged to the screen. The first column of each logged line is the time the location was generated, and second column is the time the location was received by the WebView.

@vdt2210
Copy link

vdt2210 commented Apr 15, 2023

hi @diachedelic , I just run your example with only add console.log(new Date()) in log_locaiton() and modified packages.json for match with windows command
I start run in BG in 9:33 then stop at 9:38
image
image

UPDATE: after few minutes it show this msg
image

@diachedelic
Copy link
Collaborator

Have you disabled all battery saving optimizations on your phone? Please try doing that via the Settings app, and if that doesn't fix the problem follow the instructions at https://dontkillmyapp.com/hmd-global.

@vdt2210
Copy link

vdt2210 commented Apr 16, 2023

yes, I have disabled battery saving optimizations and set example app to unrestricted. I have tested on Samsung A52s Android 13 and it's happened too
If the OS killed the app, why do the notification and the location icon remain? I am just curious this part

@diachedelic
Copy link
Collaborator

I believe the OS is probably suspending the app, rather than killing it entirely. Are you able to confirm?

@vdt2210
Copy link

vdt2210 commented Apr 17, 2023

I don't know how to confirm that correctly, but the OS may just suspend the app as you said. As I mentioned before when I modified the handleOnPause() like your comment and added background location permission and it works perfectly

@diachedelic
Copy link
Collaborator

I have attempted to reproduce the problem on my Samsung A52, running Android 13. Initially, locations stopped after one minute in the background. But after changing battery optimizations to "Unrestricted" the locations keep coming. How can it be that we are running the same app, on the same device, with the same operating system and the behaviour is different?

@vdt2210
Copy link

vdt2210 commented Apr 17, 2023

let's me check with other devices, and I will let you know the result later

@nemoneph
Copy link

@diachedelic I tried to add more details, you can look at my comment : ionic-team/capacitor#6234

@diachedelic
Copy link
Collaborator

@nemoneph
Copy link

Added a comment with a "solution" here: ionic-team/capacitor#6234 (comment)
(don't know why but my comment is hidden by default and marked as abuse.. )

ghimarcost was write, the bug has been introduced since Capacitor 4.0 =>

https://github.com/ionic-team/capacitor/releases/tag/4.0.0

"android: Use addWebMessageListener where available (ionic-team/capacitor#5427) (c2dfe80)"

@diachedelic
Copy link
Collaborator

@nemoneph has found a workaround for this problem: simply set android.useLegacyBridge to true in your Capacitor config (see https://capacitorjs.com/docs/config).

@mohamadnagi
Copy link

I added android.useLegacyBridge = true but still having the same issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests