Fix DeathRecipient leaking bug

This commit is contained in:
Mygod
2016-05-24 11:42:12 +08:00
parent 9be24d7408
commit c878d4daa6
3 changed files with 16 additions and 26 deletions
@@ -9,10 +9,11 @@ import com.github.shadowsocks.ShadowsocksApplication.app
/**
* @author Mygod
*/
trait ServiceBoundContext extends Context {
trait ServiceBoundContext extends Context with IBinder.DeathRecipient {
class ShadowsocksServiceConnection extends ServiceConnection {
override def onServiceConnected(name: ComponentName, service: IBinder) {
service.linkToDeath(new ShadowsocksDeathRecipient(ServiceBoundContext.this), 0)
binder = service
service.linkToDeath(ServiceBoundContext.this, 0)
bgService = IShadowsocksService.Stub.asInterface(service)
registerCallback
ServiceBoundContext.this.onServiceConnected()
@@ -21,6 +22,7 @@ trait ServiceBoundContext extends Context {
unregisterCallback
ServiceBoundContext.this.onServiceDisconnected()
bgService = null
binder = null
}
}
@@ -40,12 +42,14 @@ trait ServiceBoundContext extends Context {
def onServiceConnected() = ()
def onServiceDisconnected() = ()
override def binderDied = ()
private var callback: IShadowsocksServiceCallback.Stub = _
private var connection: ShadowsocksServiceConnection = _
private var callbackRegistered: Boolean = _
// Variables
var binder: IBinder = _
var bgService: IShadowsocksService = _
def attachService(callback: IShadowsocksServiceCallback.Stub = null) {
@@ -70,6 +74,10 @@ trait ServiceBoundContext extends Context {
unbindService(connection)
connection = null
}
if (binder != null) {
binder.unlinkToDeath(this, 0)
binder = null
}
bgService = null
}
}
@@ -214,6 +214,12 @@ class Shadowsocks extends AppCompatActivity with ServiceBoundContext {
if (fab != null) fab.setEnabled(false)
}
override def binderDied {
detachService
crashRecovery
attachService
}
private var testCount: Int = _
private lazy val stat = findViewById(R.id.stat)
private var connectionTestText: TextView = _
@@ -1,24 +0,0 @@
package com.github.shadowsocks
import android.os.IBinder
import android.util.Log
/**
* @author chentaov5@gmail.com
*/
class ShadowsocksDeathRecipient(val mContext: ServiceBoundContext)
extends IBinder.DeathRecipient {
val TAG = "ShadowsocksDeathRecipient"
override def binderDied(): Unit = {
Log.d(TAG, "[ShadowsocksDeathRecipient] binder died.")
mContext match {
case ss: Shadowsocks =>
ss.detachService
ss.crashRecovery
ss.attachService
case _ =>
}
}
}