notifee icon indicating copy to clipboard operation
notifee copied to clipboard

Foreground service freezes when app dismissed

Open jektvik opened this issue 1 year ago • 13 comments

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.

jektvik avatar Aug 08 '24 08:08 jektvik

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[bot] avatar Sep 05 '24 09:09 github-actions[bot]

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

jektvik avatar Sep 05 '24 09:09 jektvik

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[bot] avatar Oct 03 '24 10:10 github-actions[bot]

I am facing the same issue.

shubhamnandanwar avatar Nov 05 '24 01:11 shubhamnandanwar

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.

mikehardy avatar Nov 05 '24 01:11 mikehardy

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?

shubhamnandanwar avatar Nov 05 '24 01:11 shubhamnandanwar

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.

mikehardy avatar Nov 05 '24 02:11 mikehardy

Thanks @mikehardy for your time and suggestions :)

shubhamnandanwar avatar Nov 05 '24 02:11 shubhamnandanwar

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>

muhammadasifdotai avatar Nov 07 '24 06:11 muhammadasifdotai

@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?)

mikehardy avatar Nov 07 '24 12:11 mikehardy

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.

muhammadasifdotai avatar Nov 08 '24 06:11 muhammadasifdotai

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 avatar Nov 08 '24 12:11 mikehardy

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

mikehardy avatar Nov 08 '24 12:11 mikehardy