如何实现检测外部App启动并触发通知功能?
Hey there! Let's walk through how to build an app that detects when other apps launch and sends notifications to the user. The approach varies a lot depending on whether you're targeting Android or iOS, so I'll cover both platforms in detail below.
On Android, the most reliable way to detect app launches (especially on newer versions like Android 10+) is using an AccessibilityService. This service lets your app observe system-wide events, including when a new app's window comes to the foreground. Here's how to set it up:
Create an Accessibility Service subclass
You'll need to extendAccessibilityServiceand override theonAccessibilityEventmethod to listen for window state changes. When a new app's window becomes active, you can grab its package name and trigger a notification.Example code snippet:
class AppLaunchDetectorService : AccessibilityService() { private var lastPackageName: String? = null override fun onAccessibilityEvent(event: AccessibilityEvent?) { event?.let { if (it.eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) { val currentPackageName = it.packageName?.toString() currentPackageName?.let { pkg -> if (pkg != lastPackageName && pkg != applicationContext.packageName) { // A new app has launched sendAppLaunchNotification(pkg) lastPackageName = pkg } } } } } override fun onInterrupt() { // Handle service interruption } private fun sendAppLaunchNotification(packageName: String) { val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val channelId = "APP_LAUNCH_CHANNEL" // Create notification channel (required for Android O+) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel(channelId, "App Launch Alerts", NotificationManager.IMPORTANCE_DEFAULT) notificationManager.createNotificationChannel(channel) } val notification = NotificationCompat.Builder(this, channelId) .setContentTitle("New App Launched") .setContentText("Package: $packageName") .setSmallIcon(R.drawable.ic_notification) .build() notificationManager.notify(1, notification) } }Register the service in your Manifest
Add this entry to yourAndroidManifest.xmlto declare the service and request the necessary permission:<service android:name=".AppLaunchDetectorService" android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"> <intent-filter> <action android:name="android.accessibilityservice.AccessibilityService" /> </intent-filter> <meta-data android:name="android.accessibilityservice" android:resource="@xml/accessibility_service_config" /> </service>Create the accessibility service config file
Make a new XML fileres/xml/accessibility_service_config.xmlwith the following content to specify what events your service listens to:<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android" android:accessibilityEventTypes="typeWindowStateChanged" android:accessibilityFeedbackType="feedbackGeneric" android:accessibilityFlags="flagDefault" android:description="@string/accessibility_service_description" />Request user authorization
Accessibility services require explicit user approval. You'll need to prompt the user to enable your service in the device's Accessibility Settings. You can redirect them there with this code:val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS) startActivity(intent)
Alternative: You can also use UsageStatsManager to get app usage data, which includes launch times. However, this requires the PACKAGE_USAGE_STATS permission (also user-granted) and doesn't give real-time updates like AccessibilityService does.
iOS has strict privacy restrictions, so there's no direct API for detecting when other apps launch—Apple prohibits this for regular App Store apps to protect user privacy. That said, there are a few indirect workarounds depending on your use case:
Detect when your app is sent to the background
When another app launches, your app will be moved to the background. You can use theUIApplicationDelegatemethodsapplicationWillResignActive(_:)orapplicationDidEnterBackground(_:)to infer that another app has opened. However, this doesn't tell you which app launched—only that your app is no longer in the foreground.Example:
func applicationWillResignActive(_ application: UIApplication) { // Your app is losing focus; likely another app is launching sendNotification(title: "App Backgrounded", message: "Another app may have launched") } private func sendNotification(title: String, message: String) { let content = UNMutableNotificationContent() content.title = title content.body = message content.sound = .default let request = UNNotificationRequest(identifier: "AppBackgrounded", content: content, trigger: nil) UNUserNotificationCenter.current().add(request) }Enterprise/MDM Solutions
If you're building an app for enterprise use (not for the App Store), you can use Mobile Device Management (MDM) APIs to monitor app launches. But this requires enrollment in Apple's Enterprise Developer Program and isn't available to regular developers.
Important note: Any attempt to directly detect other app launches in a regular App Store app will likely get your app rejected during Apple's review process.
- For Android, always make sure to explain to users why you need the accessibility permission—transparency helps with user trust.
- For iOS, adjust your expectations based on Apple's privacy rules; direct detection isn't feasible for public apps.
内容的提问来源于stack exchange,提问作者Owner

