title: Android 10 swipe kills foreground service
body: <p>Background:<br />
  A third party app produces a file in <code>/sdcard/content</code>.<br />
  My app should monitor the file for changes so it can print the contents; thus i need it to be constantly running.</p>
  <p>The problems:</p>
  <ul>
  <li>on an android 10 device (Alcatel tablet), if i swipe all apps away, the service gets killed</li>
  <li>on another android 10 device (which i don't have access to), if the app is not in focus, i.e. the user is using another app, then it's not monitoring the file. If the user switches back to my app, it starts monitoring again.</li>
  </ul>
  <p>On an android 9 device that was upgraded to 10 (Galaxy A20e) the service is not killed.</p>
  <hr />
  <p>In my Main activity i have a spinner and when <code>onItemSelected</code> is called i start the service (if it wasn't already started) and bind to it:</p>
  <pre><code>if(ApplicationPersistence.isServiceStarted) {
          refreshNotification()
  } else {
          startService(Intent(this, MyService::class.java))
          bindService(Intent(this, MyService::class.java), this, Context.BIND_AUTO_CREATE or Context.BIND_IMPORTANT)
  }
  </code></pre>
  <p>I don't think you'd need to bind to a service if you want to start it as a foreground service.</p>
  <p>I see the notification. It gets updated if i change the spinner selection.<br />
  I see MyService's <code>onStartCommand</code> being called.<br />
  I see MyActivity's <code>onServiceConnected</code> being called, as well as MyService's <code>onBind</code>.</p>
  <p>MyService's <code>onStartCommand</code> acts as such:</p>
  <pre><code>override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
          if(ApplicationPersistence.isServiceStarted) {
                  return Service.START_STICKY
          }
  
          ApplicationPersistence.fileObserver.startWatching()
  
          // notification initialization here
          
          startForeground(ApplicationPersistence.notificationID, ApplicationPersistence.notification)
          ApplicationPersistence.isServiceStarted = true
          return Service.START_STICKY
  }
      
  </code></pre>
  <p><code>ApplicationPersistence</code> being the class that stores most persistent data (it <code>: Application()</code>).</p>
  <p>This is my manifest:</p>
  <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
  &lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
      package=&quot;x.y.z&quot;&gt;
  
      &lt;uses-permission android:name=&quot;android.permission.READ_EXTERNAL_STORAGE&quot; /&gt;
      &lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot; /&gt;
      &lt;uses-permission android:name=&quot;android.permission.BLUETOOTH&quot; /&gt;
      &lt;uses-permission android:name=&quot;android.permission.BLUETOOTH_ADMIN&quot; /&gt;
      &lt;uses-permission android:name=&quot;android.permission.FOREGROUND_SERVICE&quot; /&gt;
      &lt;uses-permission android:name=&quot;android.permission.WAKE_LOCK&quot; /&gt;
      &lt;uses-sdk
          android:minSdkVersion=&quot;19&quot;
          android:targetSdkVersion=&quot;21&quot; /&gt; 
  
      &lt;application
          android:allowBackup=&quot;true&quot;
          android:icon=&quot;@mipmap/ic_launcher&quot;
          android:label=&quot;@string/app_name&quot;
          android:roundIcon=&quot;@mipmap/ic_launcher_round&quot;
          android:theme=&quot;@style/Theme.AppCompat.Light.NoActionBar&quot;
          android:name=&quot;x.y.z.ApplicationPersistence&quot;
          android:directBootAware=&quot;true&quot;
          android:persistent=&quot;true&quot;
          android:persistableMode=&quot;persistAcrossReboots&quot;
          android:requestLegacyExternalStorage=&quot;true&quot;&gt;
  
          &lt;activity android:name=&quot;.MyActivity&quot;&gt;
              &lt;intent-filter&gt;
                  &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
                  &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;
              &lt;/intent-filter&gt;
          &lt;/activity&gt;
          &lt;service
              android:name=&quot;.MyService&quot;
              android:directBootAware=&quot;true&quot;
              android:description=&quot;@string/notif4&quot;
              android:stopWithTask=&quot;false&quot;/&gt;
          &lt;receiver android:name=&quot;.Receiver&quot;&gt;&lt;/receiver&gt;
      &lt;/application&gt;
  &lt;/manifest&gt;
  </code></pre>
  <p>I'm tagetting 19/21 because of storage permissions on android 10.</p>
  <hr />
  <p>I've tried using <a href="https://developer.android.com/reference/android/os/PowerManager.WakeLock" rel="nofollow noreferrer">PowerManager</a> to no avail. A <a href="https://developer.android.com/training/scheduling/wakelock#wakeful" rel="nofollow noreferrer">WakefulReceiver</a> precludes an  <a href="https://developer.android.com/reference/android/app/IntentService" rel="nofollow noreferrer">IntentService</a> which i'm not using as it'll terminate after processing the Intent. I haven't noticed any <a href="https://stackoverflow.com/questions/62305294/foreground-service-is-killed-in-android-10">battery optimization</a> issues, as i've disabled all i could find. WorkManager has a 15m <a href="https://developer.android.com/topic/libraries/architecture/workmanager/how-to/define-work#schedule_periodic_work" rel="nofollow noreferrer">minimum retry time</a> which makes it useless for this purpose. Using a <a href="https://stackoverflow.com/questions/22514373/start-a-service-in-a-separate-process-android#38318003">separate process</a> didn't work either and i lost information i post t
  to the notification.</p>
  <p>Am i missing something obvious? Music apps can do it...</p>
  <hr />
  <p><strong>Edit1</strong></p>
  <p>For the Alcatel, the last action i see in the log is the <code>MyActivity</code>'s <code>onPause()</code> being called when i tap the home button. I see no reaction when i swipe.<br />
  For the Samsung, when i swipe i see</p>
  <pre><code>D/MyActivity: onDetachedFromWindow()
  D/MyService: onTaskRemoved()
      android.app.ServiceConnectionLeaked: Activity x.y.z.MyActivity has leaked ServiceConnection x.y.z.MyActivity@ce48f05 that was originally bound here
          ...
                  at x.y.z.MyActivity.onItemSelected(MyActivity.kt:201) // the bindService call
          ...
  D/MyService: onUnbind(null)
  </code></pre>
  <hr />
  <p><strong>Edit2</strong></p>
  <p>If i check if the service <a href="https://stackoverflow.com/a/47692206/1831722">is foreground</a>, it apparently is <em>not</em> on both devices, however, adb says otherwise.</p>
  <p>Samsung</p>
  <pre><code>* ServiceRecord{92e7bc9 u0 x.y.z/.MyService}
    intent={cmp=x.y.z/.MyService}
    packageName=x.y.z
    processName=x.y.z
    baseDir=/data/app/x.y.z-3i0pcMiZVFi-apzWGR-5hw==/base.apk
    dataDir=/data/user/0/x.y.z
    app=ProcessRecord{8f822ce 20490:x.y.z/u0a210}
    isForeground=true foregroundId=1 foregroundNoti=Notification(channel=x.y.z pri=2 contentView=null vibrate=null sound=null defaults=0x0 flags=0x62 color=0x00000000 category=service vis=PRIVATE semFlags=0x0 semPriority=0 semMissedCount=0)
    createTime=-13m56s837ms startingBgTimeout=--
    lastActivity=-13m56s829ms restartTime=-13m56s837ms createdFromFg=true
    startRequested=true delayedStop=false stopIfKilled=false callStart=true lastStartId=1
    Bindings:
    * IntentBindRecord{b830b66 CREATE}:
      intent={cmp=x.y.z/.MyService}
      binder=android.os.BinderProxy@b291ea7
      requested=true received=true hasBound=true doRebind=false
      * Client AppBindRecord{4031f54 ProcessRecord{8f822ce 20490:x.y.z/u0a210}}
        Per-process Connections:
          ConnectionRecord{8ee48fc u0 CR IMP x.y.z/.MyService:@595c5ef}
    All Connections:
      ConnectionRecord{8ee48fc u0 CR IMP x.y.z/.MyService:@595c5ef}
  </code></pre>
  <p>Alcatel</p>
  <pre><code>* ServiceRecord{7872f83 u0 x.y.z/.MyService}
    intent={cmp=x.y.z/.MyService}
    packageName=x.y.z
    processName=x.y.z
    baseDir=/data/app/x.y.z-tB_tv4YEDBranjBzPXNqeg==/base.apk
    dataDir=/data/user/0/x.y.z
    app=ProcessRecord{bc00038 7463:x.y.z/u0a182}
    isForeground=true foregroundId=1 foregroundNoti=Notification(channel=x.y.z pri=2 contentView=null vibrate=null sound=null defaults=0x0 flags=0x62 color=0x00000000 category=service vis=PRIVATE)
    createTime=-26m9s402ms startingBgTimeout=--
    lastActivity=-26m9s397ms restartTime=-26m9s402ms createdFromFg=true
    startRequested=true delayedStop=false stopIfKilled=false callStart=true lastStartId=1
    Bindings:
    * IntentBindRecord{5de8688 CREATE}:
      intent={cmp=x.y.z/.MyService}
      binder=android.os.BinderProxy@1ece821
      requested=true received=true hasBound=true doRebind=false
      * Client AppBindRecord{b1f1446 ProcessRecord{bc00038 7463:x.y.z/u0a182}}
        Per-process Connections:
          ConnectionRecord{3c96139 u0 CR IMP x.y.z/.MyService:@75b5500}
    All Connections:
      ConnectionRecord{3c96139 u0 CR IMP x.y.z/.MyService:@75b5500}
  </code></pre>
  <p>There's a difference after <code>vis=PRIVATE</code> but that's it.</p>
  <hr />
  <p><strong>Edit3</strong></p>
  <p>For the most part, the service seems to be running in the foregroud.</p>
  <p>I've also implemented a method in the Service's Binder that simply waits a random amount of time (1-2s) and returns the wait time.<br />
  This, in turn, is used by the binding class (my <code>: Application()</code>) inside a thread that waits 3-4s before calling the Binder method.<br />
  This way i get &quot;server/client&quot; interaction every 3s or so, but the app is still killed on Android 10 if i swipe all apps.</p>
  <hr />
  <p><strong>Edit 4</strong></p>
  <p><s>I've also registered a lot of random broadcasts in my Activity via <code>filter.addAction()</code> to try and keep it alive.</s> I've used <code>filter.addAction(Intent.ACTION_TIME_TICK)</code> but swipe always kills the app.<br />
  Meaning the log stops, no onMethod (that I've overriden) is called; the notification is gone; the service is no longer running.</p>