flutter_foreground_task icon indicating copy to clipboard operation
flutter_foreground_task copied to clipboard

Terminate the service when the app is updated

Open thorito opened this issue 3 months ago • 0 comments

To prevent the service from closing when the app is closed, I have defined: android:stopWithTask="false". I want to make sure that after hours of running in the background, the operating system doesn't close the application.

The problem is that if the user (while the app is running) updates it from Google Play, the service remains running. When the user restarts the app, it freezes.

<service
            android:name="com.pravera.flutter_foreground_task.service.ForegroundService"
            android:foregroundServiceType="dataSync|remoteMessaging|location"
            android:stopWithTask="false"
            android:exported="false" />

<receiver
            android:name=".UpdatedReceiver"
            android:enabled="true"
            android:exported="false">
            <intent-filter>
                <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
            </intent-filter>
        </receiver>
class UpdatedReceiver : BroadcastReceiver() {
   
    override fun onReceive(context: Context, intent: Intent) {
        if (intent == Intent.ACTION_MY_PACKAGE_REPLACED) {
            try {
                val serviceIntent = Intent()
                serviceIntent.setClassName(
                    context.packageName,
                    "com.pravera.flutter_foreground_task.service.ForegroundService"
                )
                context.stopService(serviceIntent)
            } catch (e: Exception) {
                Log.e("UpdatedReceiver", "Error: ${e.message}")
            }
        }
    }
}

I created a broadcast receiver to listen when the app itself updates and try to shut down the service before the app closes.

But I don't know how to make it stop. Any ideas?

Thank you so much

thorito avatar Oct 02 '25 15:10 thorito