From d2a10272294990816cde2bea8a2cccb23b0dd2b4 Mon Sep 17 00:00:00 2001 From: Max Lv Date: Sat, 5 Dec 2015 17:32:56 +0800 Subject: [PATCH] Fix an issue of attach/deattach service when switching NAT mode --- .../github/shadowsocks/ServiceBoundContext.scala | 14 +++++++++++--- .../github/shadowsocks/ShadowsocksSettings.scala | 11 +++++++---- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/src/main/scala/com/github/shadowsocks/ServiceBoundContext.scala b/src/main/scala/com/github/shadowsocks/ServiceBoundContext.scala index 1dc247bb..e6cbbeaf 100644 --- a/src/main/scala/com/github/shadowsocks/ServiceBoundContext.scala +++ b/src/main/scala/com/github/shadowsocks/ServiceBoundContext.scala @@ -9,7 +9,8 @@ import com.github.shadowsocks.utils.Action * @author Mygod */ trait ServiceBoundContext extends Context { - val connection = new ServiceConnection { + + class ShadowsocksServiceConnection extends ServiceConnection { override def onServiceConnected(name: ComponentName, service: IBinder) { bgService = IShadowsocksService.Stub.asInterface(service) if (callback != null) try { @@ -37,6 +38,7 @@ trait ServiceBoundContext extends Context { def onServiceDisconnected() = () private var callback: IShadowsocksServiceCallback.Stub = _ + private var connection: ShadowsocksServiceConnection = _ // Variables var bgService: IShadowsocksService = _ @@ -46,9 +48,13 @@ trait ServiceBoundContext extends Context { if (bgService == null) { val s = if (ShadowsocksApplication.isVpnEnabled) classOf[ShadowsocksVpnService] else classOf[ShadowsocksNatService] + val intent = new Intent(this, s) intent.setAction(Action.SERVICE) + + connection = new ShadowsocksServiceConnection() bindService(intent, connection, Context.BIND_AUTO_CREATE) + startService(new Intent(this, s)) } } @@ -62,8 +68,10 @@ trait ServiceBoundContext extends Context { case ignored: RemoteException => // Nothing } } - unbindService(connection) - bgService = null + if (connection != null) { + unbindService(connection) + connection = null + } } } } diff --git a/src/main/scala/com/github/shadowsocks/ShadowsocksSettings.scala b/src/main/scala/com/github/shadowsocks/ShadowsocksSettings.scala index 0831eee7..684fc0ed 100644 --- a/src/main/scala/com/github/shadowsocks/ShadowsocksSettings.scala +++ b/src/main/scala/com/github/shadowsocks/ShadowsocksSettings.scala @@ -73,10 +73,13 @@ class ShadowsocksSettings extends PreferenceFragment with OnSharedPreferenceChan } def onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) = key match { - case Key.isNAT => if (ShadowsocksApplication.isRoot) activity.handler.post(() => { - activity.deattachService() - activity.attachService() - }) + case Key.isNAT => if (ShadowsocksApplication.isRoot && activity != null) { + activity.handler.post(() => { + val intent = activity.getIntent + activity.finish() + startActivity(intent) + }) + } case _ => } }