You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin.Forms前台服务导致应用杀死后无法重启问题求助

Fixes for App Restart Issue with Xamarin.Forms Foreground Service

Hey there, let's figure out why your app won't launch after being killed while running a foreground service. I've gone through your code and found several key issues that are likely causing this problem, plus actionable fixes:


1. Critical Typo in Stop Service Method

Looking at your MainActivity.cs code, there's a typo in the StopServiceFromApp method that prevents the service from being properly stopped:

public void StopServiceFromApp()
{
    // Wrong class name: ScoularService instead of MyPrjService
    var intent1 = new Intent(this, typeof(ScoularService));
    StopService(intent1);
}

Fix: Replace ScoularService with your actual service class MyPrjService:

public void StopServiceFromApp()
{
    var intent1 = new Intent(this, typeof(MyPrjService));
    StopService(intent1);
}

When the service isn't stopped correctly, it keeps running in the background even after the app is closed. This creates conflicts when you try to restart the app, leading to launch failures.


2. Adjust Foreground Service Restart Behavior

You're returning StartCommandResult.Sticky from OnStartCommand, which tells Android to automatically restart the service if it's killed. However, when a user manually kills the app, Android ties the service to the app's process—restarting the app while the sticky service is still trying to run can cause process conflicts.

Fix Options:

  • If you don't need the service to restart independently of the app, switch to StartCommandResult.NotSticky:
    public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
    {
        StartLocationServiceForeground();
        return StartCommandResult.NotSticky;
    }
    
  • If you require the sticky behavior, add a check in the service to verify if the app's main activity is running before proceeding, to avoid conflicts on app restart.

3. Add Notification Click Intent to Reopen the App

Your foreground notification doesn't have a click handler to launch the app. When the app is killed, the notification remains but does nothing when tapped—this makes it seem like the app won't open.

Fix: Add a PendingIntent to your notification builder in StartLocationServiceForeground:

void StartLocationServiceForeground()
{
    try
    {
        if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
        {
            var chan1 = new NotificationChannel(LOCATION_CHANNEL, new Java.Lang.String("Primary"), NotificationImportance.High);
            manager.CreateNotificationChannel(chan1);
            notification = new NotificationCompat.Builder(Forms.Context, LOCATION_CHANNEL);

            // Add intent to open MainActivity when notification is tapped
            var openAppIntent = new Intent(this, typeof(MainActivity));
            openAppIntent.AddFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop);
            var pendingIntent = PendingIntent.GetActivity(this, 0, openAppIntent, PendingIntentFlags.UpdateCurrent);

            notification.SetOngoing(true)
                .SetSmallIcon(Resource.Drawable.icon_transparent)
                .SetContentTitle("MyPrj is running background")
                .SetContentText("Tap for more information or to stop the app")
                .SetColor(0x9c6114)
                .SetPriority(NotificationCompat.PriorityHigh)
                .SetContentIntent(pendingIntent); // Attach the intent

            StartForeground(1, notification.Build());
        }
    }
    catch(System.Exception ex)
    {
        logger.Error(ex, "Failed to start foreground service");
    }
}

4. Handle Android Background Service Restrictions

Android 10 (API 29) and later impose strict limits on starting services from the background. Your OnSleep method tries to start the service, which may be blocked by the system.

Fixes:

  • Add the required permissions to your AndroidManifest.xml:
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <!-- For Android 13+, add notification permission -->
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
    
  • For Android 10+, consider using WorkManager for background tasks, or catch ForegroundServiceStartNotAllowedException and handle it gracefully (e.g., show a notification asking the user to open the app to resume the service).

5. Clean Up Resources Properly

Your service has a _cts (CancellationTokenSource) declared but not used in OnDestroy. Failing to cancel and dispose of it can lead to memory leaks, which might cause unexpected behavior when restarting the app.

Fix: Update your OnDestroy method:

public override void OnDestroy()
{
    _cts?.Cancel();
    _cts?.Dispose();
    StopForeground(true);
    manager?.CancelAll();
    base.OnDestroy();
}

Final Steps to Test

  1. Apply all the fixes above
  2. Uninstall the app from your device/emulator completely
  3. Reinstall and test: put the app to sleep, kill it, then try restarting it or tapping the foreground notification

内容的提问来源于stack exchange,提问作者Manthiram

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:58:54