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

Foreground service freezes when app dismissed #1078

Open
jektvik opened this issue Aug 8, 2024 · 13 comments
Open

Foreground service freezes when app dismissed #1078

jektvik opened this issue Aug 8, 2024 · 13 comments
Labels
Keep Open this label avoids the stale bot

Comments

@jektvik
Copy link
Contributor

jektvik commented Aug 8, 2024

Have tried about just about every config concievable to get the foreground service running but it just won't continue executing as soon as I dismiss the parent app to the background.

await notifee.registerForegroundService((notification: Notification) => {
    return new Promise(resolve => {
      const interval2 = setInterval(() => console.log('testmessage'), 6000);

      notifee.onBackgroundEvent(async event => {
        if (event.type === EventType.DISMISSED) {

          await notifee.cancelNotification(notification.id || '');
          console.log('Handled DISMISSED onBackgroundEvent');
        }

        return resolve();
      });

      notifee.onForegroundEvent(async event => {
        if (event.type === EventType.DISMISSED) {
          await notifee.cancelNotification(notification.id || '');
        }

        return resolve();
      });
    });
  });
```

The above 'test message' will continue displaying every 6 s as long as the app is on the foreground but as soon as I return to main screen that execution freezes (i.e. it's not properly attached to the foreground service). When I open the app again, it may unfreeze.
The testmessage code is meant to actually be a 'refreshNotification' type of function, but it never worked therefore I'm attaching this simplified example.

Android logs keep spamming
`08-08 10:55:06.711   583   818 W IPCThreadState: Sending oneway calls to frozen process.`

Which I think may be indicative of what the issue is, i.e. the setInterval function isn't properly attached to any process (foregroundProcess?) which is meant to stay alive when the app is in the background.

Similarly, functions like

  await notifee.stopForegroundService();
  await notifee.cancelAllNotifications();
  
  seem to have no effect, i.e. even after I call them, the interval messages will keep executing if they'd been started like above.
Copy link

github-actions bot commented Sep 5, 2024

Hello 👋, to help manage issues we automatically close stale issues.

This issue has been automatically marked as stale because it has not had activity for quite some time.Has this issue been fixed, or does it still require attention?

This issue will be closed in 15 days if no further activity occurs.

Thank you for your contributions.

@jektvik
Copy link
Contributor Author

jektvik commented Sep 5, 2024

This issue has been automatically marked as stale because it has not had activity for quite some time.Has this issue been fixed, or does it still require attention?
Defeinitely still alive

Copy link

github-actions bot commented Oct 3, 2024

Hello 👋, to help manage issues we automatically close stale issues.

This issue has been automatically marked as stale because it has not had activity for quite some time.Has this issue been fixed, or does it still require attention?

This issue will be closed in 15 days if no further activity occurs.

Thank you for your contributions.

@github-actions github-actions bot closed this as not planned Won't fix, can't repro, duplicate, stale Oct 18, 2024
@shubhamnandanwar
Copy link

I am facing the same issue.

@mikehardy mikehardy added Keep Open this label avoids the stale bot and removed Type: Stale labels Nov 5, 2024
@mikehardy mikehardy reopened this Nov 5, 2024
@mikehardy
Copy link
Contributor

I can reopen this but there is a very constrained amount of dev time I have - if anyone that is affected by this can dig in to troubleshoot it, that's the way to move this forward.

Note that this may be affected by new architecture being enabled or not - if you are on react-native 0.76+ with bridgeless enabled this package is mostly working but there are reports that the new architecture mode causes foreground-service freezing. That may be the same issue as originally logged here it may not, I am unsure. But testing with new architecture enabled vs disabled is a good first step at diagnosis. Beyond that, unsure.

@shubhamnandanwar
Copy link

Hey @mikehardy, I don't have access to Android 14 but a lot of users has reported this issue. My app has a timer feature that users a foreground service to resume/pause the timer. The feature works fine initially but after around 5 minutes closing the app, it freezes. Nothing works. I am not able to recreate it on Emulator. Do you know how it can be recreated? Also, is there a workaround to fix the freeze temporarily?

@mikehardy
Copy link
Contributor

I wasn't even aware this is a problem as I don't use the module like this in any way - so I don't reproduce it either and I'm unaware of any workarounds. The only thing I know is that it may be related to new architecture. But it may not.

Someone who is impacted and motivated to troubleshoot will have to start instrumenting the code and finding reproduction scenarios and determine a root cause. Getting access to an Android 14 phone should be possible on the used market perhaps if a real device (not emulator) is required to reproduce.

Perhaps someone else impacted is able to reproduce this on the emulator, that would be useful to know if so.

@shubhamnandanwar
Copy link

Thanks @mikehardy for your time and suggestions :)

@muhammadasifdotai
Copy link

muhammadasifdotai commented Nov 7, 2024

Android 14: Foreground Service works on Foreground but not on Background

I'm experiencing an issue where the foreground service works as expected while the app is in the foreground but stops working when the app is in the background on Android 14. This setup works perfectly on Android 13, where the service continues to run in both foreground and background. Here are my details:

  • React Native version: 0.75.3
  • Notifee version: "@notifee/react-native": "^9.1.2"
  • Android version: 14

Code Implementation

Foreground Service Start Code:

const startForegroundService = async () => {
  if (Platform.OS === 'android' && Platform.Version >= 26) {
    // Step 1: Create a notification channel
    await notifee.createChannel({
      id: 'locationChannel',
      name: 'Location Tracking Channel',
      importance: AndroidImportance.LOW, // Adjust as necessary
    });
  }

  // Step 2: Register a minimal foreground service
  notifee.registerForegroundService(async () => {
    // Minimal function with no interval or tasks to reduce strain on the main thread
    return new Promise(() => {
      console.log("Foreground service registered.");
    });
  });

  // Step 3: Display the notification as a foreground service
  await notifee.displayNotification({
    title: 'Tracking location updates',
    body: 'Tracking location of user',
    android: {
      channelId: 'locationChannel',
      asForegroundService: true,
      smallIcon: 'ic_launcher', // Ensure this icon exists in res/drawable
    },
  });
};

**Foreground Service Stop Code:**

```javascript
const stopForegroundService = async () => {
  try {
    await notifee.stopForegroundService();
    console.log("Foreground service stopped.");
  } catch (error) {
    console.error('Failed to stop foreground service:', error);
  }
};




### Expected Behavior
- The foreground service should continue running in the background and display location tracking updates as a notification.

### Actual Behavior
- The foreground service stops when the app goes into the background on Android 14.





### AndroidManifest.xml Configuration

Here is my `AndroidManifest.xml` setup, including permissions and service configurations:

```xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />

    <application
      android:name=".MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:allowBackup="false"
      android:theme="@style/AppTheme"
      android:supportsRtl="true">
      <meta-data
     android:name="com.google.android.geo.API_KEY"
     android:value="AIzaSyDxn5xb9-opF0sOL8SUl33yOplQ6qZebvk"/>
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
        android:launchMode="singleTask"
        android:windowSoftInputMode="adjustResize"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>

      <!-- Notifee Foreground Service -->
        <service
            android:name="app.notifee.core.ForegroundService"
            android:foregroundServiceType="location"
            tools:replace="android:foregroundServiceType" />
    </application>
</manifest>

@mikehardy
Copy link
Contributor

@muhammadasifdotai thank you for the details! May I ask a couple followon questions?

  • are you using new architecture (fabric) or old architecture (paper)? If you are using fabric, are you running in bridgeless mode or not?
  • are you able to reproduce this on android 13 vs android 14 emulators? Or only real devices? Is it only android 14 where it freezes or is it actually any android >= 14? (that is 15 also fails, or does it?)

@muhammadasifdotai
Copy link

muhammadasifdotai commented Nov 8, 2024

1. Architecture

I'm using the old architecture (Paper).

2. Testing Results

  • Android 13 (physical device): Works as expected.
  • ⚠️ Android 14 (physical device): After testing on Pixel 5 (Android 14) and Pixel 6 (Android 14), the issue seems to be isolated to the Pixel 6. It works fine on the Pixel 5, but the location service doesn’t continue in the background on the Pixel 6, despite both devices being on Android 14.
  • ✅ Android 15 (emulator): Works correctly and continues to provide the location without freezing.
  • ✅ Android 15 (physical device): Works correctly and continues to provide the location in the background without freezing.

@mikehardy
Copy link
Contributor

Hmm - I wonder if any of the suggestions from https://dontkillmyapp.com/ would help with your android 14 case
I have a Pixel 6a running Android 14 by sheer chance, so I may be able to reproduce this, but if there was any way it could be triggered in an emulator that would be (rough estimation...) 1000x more useful 😅

@mikehardy
Copy link
Contributor

Also, even if the only device reproducing it is your physical android 14 device I strongly encourage you to plug in to your development computer during reproduction and adb logcat > bg-freeze-logcat-repro.txt so we can examine what the system is doing when it "decides" to stop the notification

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Keep Open this label avoids the stale bot
Projects
None yet
Development

No branches or pull requests

4 participants