Skip to content

Commit e20bc3d

Browse files
committed
More correctly manage VPN service lifetime
Previously we never explicitly stopped, we just moved to the background. Later we got killed (very reasonably), and then afterwards we got restarted (because we're sticky) but with a null intent, which makes Kotlin unhappy. Now we either stop properly, or ask for the intent to be redelivered correctly.
1 parent e607435 commit e20bc3d

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

app/src/main/java/tech/httptoolkit/android/ProxyVpnService.kt

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,16 @@ class ProxyVpnService : VpnService(), IProtectSocket {
5050
private var vpnInterface: ParcelFileDescriptor? = null
5151
private var vpnRunnable: ProxyVpnRunnable? = null
5252

53+
override fun onCreate() {
54+
super.onCreate()
55+
currentService = this
56+
}
57+
58+
override fun onDestroy() {
59+
super.onDestroy()
60+
currentService = null
61+
}
62+
5363
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
5464
currentService = this
5565
Log.i(TAG, "onStartCommand called")
@@ -63,11 +73,17 @@ class ProxyVpnService : VpnService(), IProtectSocket {
6373
if (intent.action == START_VPN_ACTION) {
6474
val proxyConfig = intent.getParcelableExtra<ProxyConfig>(PROXY_CONFIG_EXTRA)
6575
startVpn(proxyConfig)
76+
77+
// If the system briefly kills us for some reason (memory, the user, whatever) whilst
78+
// running the VPN, it should redeliver the VPN setup intent ASAP.
79+
return Service.START_REDELIVER_INTENT
6680
} else if (intent.action == STOP_VPN_ACTION) {
6781
stopVpn()
6882
}
6983

70-
return Service.START_STICKY
84+
// Shouldn't matter (we should've stopped already), but in general: if we're not running a
85+
// VPN, then the service doesn't need to be sticky.
86+
return Service.START_NOT_STICKY
7187
}
7288

7389
override fun onRevoke() {
@@ -160,6 +176,8 @@ class ProxyVpnService : VpnService(), IProtectSocket {
160176

161177
stopForeground(true)
162178
localBroadcastManager!!.sendBroadcast(Intent(VPN_STOPPED_BROADCAST))
179+
stopSelf()
180+
currentService = null
163181
}
164182

165183
fun isActive(): Boolean {

0 commit comments

Comments
 (0)