关闭Activity后Service停止运行,调试器自动断开的排查求助
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
AndroidRuntimeentries — 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 incomingIntentmight be null or have no action. Your current code callsstopSelf()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 callstartForeground()to keep the service running:
Make sure yoursetupNotification()includes this line:
Withoutprivate 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); }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
- Set up the debugger attachment settings as mentioned earlier
- Add breakpoints in key service methods (
onStartCommand,onDestroy,receivedMessage,found) - Launch the app, start the service, then close the MainActivity
- 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

