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

关闭Activity后Service停止运行,调试器自动断开的排查求助

Fix: Service Stops When Activity Closes + Debugger Disconnects

Hey there, let's break down the two issues you're facing: your debugger disconnects when closing the MainActivity, and your supposed-to-be-running-in-background MainService stops along with it. Here's how to tackle both:

First: Keep the Debugger Attached to Catch Background Crashes

The debugger disconnecting usually means your app process is getting killed (either by the system or a crash), but we can tweak settings to keep it stuck to your process:

1. Force Debugger to Stay Attached

  • Open Android Studio's Run/Debug Configurations (click the dropdown next to the run button → Edit Configurations)
  • Find your app's config, switch to the Debugger tab
  • Check the box for Wait for debugger to attach (this makes the app wait until the debugger connects before launching, which helps with background processes)
  • On your phone, go to Developer Options → Debug app, select your app's package name
  • Turn on Wait for debugger (some devices call this "Keep awake during debugging" — it ensures the debugger doesn't drop when the app goes to the background)

2. Bypass System Process Restrictions

Lots of Android OEMs (like Xiaomi, Huawei, Samsung) have aggressive background process killing. To work around this:

  • In Developer Options, set Background process limit to Standard limit
  • Manually add your app to the system's "protected apps" list (path varies by device: e.g., Xiaomi → Battery Saver → App Battery Saver → Your App → Set to "No restrictions")

Second: Figure Out Why Your Service Is Stopping

You're returning START_STICKY from onStartCommand, which should make the system restart the service if it's killed — but if the process crashes (unhandled exception) or your service has logic flaws, it won't stay running. Let's check the common culprits:

1. Check Crash Logs (Even If Debugger Disconnects)

Don't rely solely on the debugger — use Logcat to catch crashes:

  • In Android Studio's Logcat window, filter by your app's package name or set the log level to Error
  • Close the Activity and watch for AndroidRuntime entries — these will show you the exact exception that's crashing your process.

2. Fix Service Lifecycle Logic

Looking at your MainService code, there are a couple of red flags:

  • Unknown Action Triggers stopSelf(): If the system restarts your service (after a crash or memory reclaim), the incoming Intent might be null or have no action. Your current code calls stopSelf() in that case, which immediately kills the service. Fix this:
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            String action = intent.getAction();
            if (ACTION_RECEIVED.equals(action)) {
                log("Received Message");
                Bundle extras = intent.getExtras();
                if (extras != null) {
                    String msg = extras.getString("msg");
                    String sender = extras.getString("sender");
                    receivedMessage(msg, sender);
                } else {
                    log("There was no message");
                }
            } else if(ACTION_FOUND.equals(action)) {
                log("Received Found");
                found();
            } else if (ACTION_START.equals(action)) {
                log("Starting MainService");
                setupNotification();
                Toast.makeText(this, "Service Running", Toast.LENGTH_LONG).show();
            } else {
                // Don't stop the service — restart it with the correct action instead
                log("Unknown action received; restarting service with START action");
                startService(new Intent(this, MainService.class).setAction(ACTION_START));
            }
        } else {
            // System restarted the service with a null intent — reinitialize it
            log("Intent is null; restarting service with START action");
            startService(new Intent(this, MainService.class).setAction(ACTION_START));
        }
        return START_STICKY;
    }
    
  • Missing Foreground Service Call: On Android 8.0+ (API 26), background services are severely restricted. Your setupNotification() method needs to call startForeground() to keep the service running:
    Make sure your setupNotification() includes this line:
    private void setupNotification() {
        // Build your notification here (you probably already have this code)
        Notification notification = yourNotificationBuilder.build();
        // This line is critical — it marks the service as foreground
        startForeground(notificationID, notification);
    }
    
    Without startForeground(), Android will kill your service minutes after the Activity closes.

3. Verify Permissions

Your service uses RECEIVE_SMS permission, but your Activity's checkPermissions() only mentions READ_EXTERNAL_STORAGE (assuming that's what's inside the method). Make sure you're checking for all required permissions:

private boolean checkPermissions() {
    return ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
            && ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) == PackageManager.PERMISSION_GRANTED;
}

If RECEIVE_SMS isn't granted, any code in your service that tries to handle SMS will throw a security exception and crash the process.

Final Debugging Workflow

  1. Set up the debugger attachment settings as mentioned earlier
  2. Add breakpoints in key service methods (onStartCommand, onDestroy, receivedMessage, found)
  3. Launch the app, start the service, then close the MainActivity
  4. Watch the debugger for breakpoint hits, or check Logcat for errors

This should help you pinpoint exactly why your service is stopping, while keeping the debugger connected to debug in real time.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:15:33