The goal is simple: to start an app when S Pen is detached. It is clear that it should be a service running even when the app is not running. This answer provides a good example of how to create a service to listen S Pen detachment by registering a receiver with BOOT_COMPLETED action. It does not matter whether you start your service from the app activity, or by registering a receiver - it works fine if you just "close" the app using Back button. But if you go to the list of recent apps and clear the app out of the list - the service stops and it does not work until you restart the device again. Does anyone have an idea how to keep listening the S Pen detachment even after the app was cleared out of the Recent Apps list?
Register a Broadcast Receiver for com.samsung.pen.INSERT
as described in this answer: Bring your app to the front when S Pen detached in android note?