11package org .osservatorionessuno .bugbane .utils ;
22
3+ import android .annotation .SuppressLint ;
34import android .app .Notification ;
45import android .app .NotificationChannel ;
56import android .app .NotificationManager ;
1213import android .os .Build ;
1314import android .os .IBinder ;
1415import androidx .annotation .Nullable ;
16+ import androidx .annotation .RequiresApi ;
17+
1518import android .util .Log ;
1619
1720import java .net .InetAddress ;
@@ -65,6 +68,8 @@ public void onCreate() {
6568 nm .createNotificationChannel (channel );
6669 }
6770
71+ // See docs below on ServiceInfo.FOREGROUND_SERVICE_TYPE_SHORT_SERVICE
72+ @ SuppressLint ("InlinedApi" )
6873 @ Override
6974 public int onStartCommand (@ Nullable Intent intent , int flags , int startId ) {
7075 Notification notification = null ;
@@ -88,7 +93,14 @@ public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
8893 }
8994 if (notification != null ) {
9095 try {
91- startForeground (NOTIFICATION_ID , notification , ServiceInfo .FOREGROUND_SERVICE_TYPE_SPECIAL_USE );
96+ // From https://developer.android.com/reference/android/content/pm/ServiceInfo:
97+ // [E]ven though FOREGROUND_SERVICE_TYPE_SHORT_SERVICE was added on Android version
98+ // Build.VERSION_CODES.UPSIDE_DOWN_CAKE, it can be also used on on prior android
99+ // versions (just like other new foreground service types can be used).
100+ // However, because Service.onTimeout(int) did not exist on prior versions, it will
101+ // never called on such versions. Because of this, developers must make sure to stop
102+ // the foreground service even if Service.onTimeout(int) is not called on such versions.
103+ startForeground (NOTIFICATION_ID , notification , ServiceInfo .FOREGROUND_SERVICE_TYPE_SHORT_SERVICE );
92104 } catch (Throwable th ) {
93105 Log .e (TAG , "startForeground failed" , th );
94106 getSystemService (NotificationManager .class ).notify (NOTIFICATION_ID , notification );
@@ -123,6 +135,13 @@ public void onDestroy() {
123135 stopSearch ();
124136 }
125137
138+ @ RequiresApi (Build .VERSION_CODES .UPSIDE_DOWN_CAKE )
139+ @ Override
140+ public void onTimeout (int service ) {
141+ // Called by system if SHORT_SERVICE exceeds 3 minute lifespan
142+ stopSelf ();
143+ }
144+
126145 private Notification onStart () {
127146 startSearch ();
128147 return searchingNotification ();
0 commit comments