diff --git a/V2rayNG/app/build.gradle b/V2rayNG/app/build.gradle
index 2a4086bb..1f5dbeb8 100644
--- a/V2rayNG/app/build.gradle
+++ b/V2rayNG/app/build.gradle
@@ -25,12 +25,14 @@ android {
minifyEnabled false
zipAlignEnabled false
shrinkResources false
+ ndk.abiFilters 'x86', 'x86_64', 'armeabi-v7a', 'arm64-v8a'
// proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
debug {
minifyEnabled false
zipAlignEnabled false
shrinkResources false
+ ndk.abiFilters 'x86', 'x86_64', 'armeabi-v7a', 'arm64-v8a'
}
}
@@ -67,7 +69,6 @@ android {
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
testImplementation 'junit:junit:4.13'
- implementation project(':dpreference')
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion"
implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion"
@@ -89,6 +90,7 @@ dependencies {
implementation 'com.android.support.constraint:constraint-layout:2.0.1'
// DSL
+ implementation 'com.tencent:mmkv-static:1.0.19'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'io.reactivex:rxjava:1.3.4'
implementation 'io.reactivex:rxandroid:1.2.1'
diff --git a/V2rayNG/app/src/main/AndroidManifest.xml b/V2rayNG/app/src/main/AndroidManifest.xml
index bc377599..543343ae 100644
--- a/V2rayNG/app/src/main/AndroidManifest.xml
+++ b/V2rayNG/app/src/main/AndroidManifest.xml
@@ -60,13 +60,7 @@
android:name=".ui.ServerActivity"
android:windowSoftInputMode="stateUnchanged" />
-
-
diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/AngApplication.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/AngApplication.kt
index 649e0594..38787b78 100644
--- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/AngApplication.kt
+++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/AngApplication.kt
@@ -2,8 +2,7 @@ package com.v2ray.ang
import android.support.multidex.MultiDexApplication
import android.support.v7.preference.PreferenceManager
-import com.v2ray.ang.util.AngConfigManager
-import me.dozen.dpreference.DPreference
+import com.tencent.mmkv.MMKV
class AngApplication : MultiDexApplication() {
companion object {
@@ -14,8 +13,6 @@ class AngApplication : MultiDexApplication() {
var firstRun = false
private set
- val defaultDPreference by lazy { DPreference(this, packageName + "_preferences") }
-
override fun onCreate() {
super.onCreate()
@@ -27,6 +24,6 @@ class AngApplication : MultiDexApplication() {
defaultSharedPreferences.edit().putInt(PREF_LAST_VERSION, BuildConfig.VERSION_CODE).apply()
//Logger.init().logLevel(if (BuildConfig.DEBUG) LogLevel.FULL else LogLevel.NONE)
- AngConfigManager.inject(this)
+ MMKV.initialize(this)
}
}
diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/AppConfig.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/AppConfig.kt
index fd4af4b4..8fd58789 100644
--- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/AppConfig.kt
+++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/AppConfig.kt
@@ -6,18 +6,43 @@ package com.v2ray.ang
*/
object AppConfig {
const val ANG_PACKAGE = "com.v2ray.ang"
- const val ANG_CONFIG = "ang_config"
- const val PREF_CURR_CONFIG = "pref_v2ray_config"
- const val PREF_CURR_CONFIG_GUID = "pref_v2ray_config_guid"
- const val PREF_CURR_CONFIG_NAME = "pref_v2ray_config_name"
- const val PREF_CURR_CONFIG_DOMAIN = "pref_v2ray_config_domain"
- const val PREF_CURR_CONFIG_OUTBOUND_TAGS = "pref_v2ray_config_outbound_tags"
- const val PREF_INAPP_BUY_IS_PREMIUM = "pref_inapp_buy_is_premium"
- const val PREF_MODE = "pref_mode"
- const val VMESS_PROTOCOL: String = "vmess://"
- const val SS_PROTOCOL: String = "ss://"
- const val SOCKS_PROTOCOL: String = "socks://"
+ // legacy
+ const val ANG_CONFIG = "ang_config"
+ const val PREF_INAPP_BUY_IS_PREMIUM = "pref_inapp_buy_is_premium"
+ const val PREF_ROUTING_CUSTOM = "pref_routing_custom"
+
+ // Preferences mapped to MMKV
+ const val PREF_MODE = "pref_mode"
+ const val PREF_SPEED_ENABLED = "pref_speed_enabled"
+ const val PREF_SNIFFING_ENABLED = "pref_sniffing_enabled"
+ const val PREF_PROXY_SHARING = "pref_proxy_sharing_enabled"
+ const val PREF_LOCAL_DNS_ENABLED = "pref_local_dns_enabled"
+ const val PREF_REMOTE_DNS = "pref_remote_dns"
+ const val PREF_DOMESTIC_DNS = "pref_domestic_dns"
+ const val PREF_FORWARD_IPV6 = "pref_forward_ipv6"
+ const val PREF_ROUTING_DOMAIN_STRATEGY = "pref_routing_domain_strategy"
+ const val PREF_ROUTING_MODE = "pref_routing_mode"
+ const val PREF_V2RAY_ROUTING_AGENT = "pref_v2ray_routing_agent"
+ const val PREF_V2RAY_ROUTING_DIRECT = "pref_v2ray_routing_direct"
+ const val PREF_V2RAY_ROUTING_BLOCKED = "pref_v2ray_routing_blocked"
+ const val PREF_PER_APP_PROXY = "pref_per_app_proxy"
+ const val PREF_PER_APP_PROXY_SET = "pref_per_app_proxy_set"
+ const val PREF_BYPASS_APPS = "pref_bypass_apps"
+ // const val PREF_BYPASS_MAINLAND = "pref_bypass_mainland"
+ // const val PREF_START_ON_BOOT = "pref_start_on_boot"
+ // const val PREF_MUX_ENAimport libv2ray.Libv2rayBLED = "pref_mux_enabled"
+ // const val PREF_SOCKS_PORT = "pref_socks_port"
+// const val PREF_HTTP_PORT = "pref_http_port"
+ // const val PREF_DONATE = "pref_donate"
+ // const val PREF_LICENSES = "pref_licenses"
+// const val PREF_FEEDBACK = "pref_feedback"
+// const val PREF_TG_GROUP = "pref_tg_group"
+ // const val PREF_AUTO_RESTART = "pref_auto_restart"
+
+ const val HTTP_PROTOCOL: String = "http://"
+ const val HTTPS_PROTOCOL: String = "https://"
+
const val BROADCAST_ACTION_SERVICE = "com.v2ray.ang.action.service"
const val BROADCAST_ACTION_ACTIVITY = "com.v2ray.ang.action.activity"
const val BROADCAST_ACTION_WIDGET_CLICK = "com.v2ray.ang.action.widget.click"
@@ -28,9 +53,6 @@ object AppConfig {
const val TASKER_EXTRA_BUNDLE_GUID = "tasker_extra_bundle_guid"
const val TASKER_DEFAULT_GUID = "Default"
- const val PREF_V2RAY_ROUTING_AGENT = "pref_v2ray_routing_agent"
- const val PREF_V2RAY_ROUTING_DIRECT = "pref_v2ray_routing_direct"
- const val PREF_V2RAY_ROUTING_BLOCKED = "pref_v2ray_routing_blocked"
const val TAG_AGENT = "proxy"
const val TAG_DIRECT = "direct"
const val TAG_BLOCKED = "block"
diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/EConfigType.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/EConfigType.kt
index 0f98ff7b..3f12160f 100644
--- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/EConfigType.kt
+++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/EConfigType.kt
@@ -1,12 +1,14 @@
package com.v2ray.ang.dto
-enum class EConfigType(val value: Int) {
- VMESS(1),
- CUSTOM(2),
- SHADOWSOCKS(3),
- SOCKS(4);
+enum class EConfigType(val value: Int, val protocolScheme: String) {
+ VMESS(1, "vmess://"),
+ CUSTOM(2, ""),
+ SHADOWSOCKS(3, "ss://"),
+ SOCKS(4, "socks://"),
+ VLESS(5, "vless://"),
+ TROJAN(6, "trojan://");
companion object {
fun fromInt(value: Int) = values().firstOrNull { it.value == value }
}
-}
\ No newline at end of file
+}
diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/ServerAffiliationInfo.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/ServerAffiliationInfo.kt
new file mode 100644
index 00000000..bb4d20be
--- /dev/null
+++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/ServerAffiliationInfo.kt
@@ -0,0 +1,10 @@
+package com.v2ray.ang.dto
+
+data class ServerAffiliationInfo(var testDelayMillis: Long = 0L) {
+ fun getTestDelayString(): String {
+ if (testDelayMillis == 0L) {
+ return ""
+ }
+ return testDelayMillis.toString() + "ms"
+ }
+}
diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/ServerConfig.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/ServerConfig.kt
new file mode 100644
index 00000000..977be96f
--- /dev/null
+++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/ServerConfig.kt
@@ -0,0 +1,69 @@
+package com.v2ray.ang.dto
+
+import com.v2ray.ang.AppConfig.TAG_AGENT
+import com.v2ray.ang.AppConfig.TAG_BLOCKED
+import com.v2ray.ang.AppConfig.TAG_DIRECT
+import com.v2ray.ang.util.Utils
+
+data class ServerConfig(
+ val configVersion: Int = 3,
+ val configType: EConfigType,
+ var subscriptionId: String = "",
+ val addedTime: Long = System.currentTimeMillis(),
+ var remarks: String = "",
+ val outboundBean: V2rayConfig.OutboundBean? = null,
+ var fullConfig: V2rayConfig? = null
+) {
+ companion object {
+ fun create(configType: EConfigType): ServerConfig {
+ when(configType) {
+ EConfigType.VMESS, EConfigType.VLESS ->
+ return ServerConfig(
+ configType = configType,
+ outboundBean = V2rayConfig.OutboundBean(
+ protocol = configType.name.toLowerCase(),
+ settings = V2rayConfig.OutboundBean.OutSettingsBean(
+ vnext = listOf(V2rayConfig.OutboundBean.OutSettingsBean.VnextBean(
+ users = listOf(V2rayConfig.OutboundBean.OutSettingsBean.VnextBean.UsersBean())))),
+ streamSettings = V2rayConfig.OutboundBean.StreamSettingsBean()))
+ EConfigType.CUSTOM ->
+ return ServerConfig(configType = configType)
+ EConfigType.SHADOWSOCKS, EConfigType.SOCKS, EConfigType.TROJAN ->
+ return ServerConfig(
+ configType = configType,
+ outboundBean = V2rayConfig.OutboundBean(
+ protocol = configType.name.toLowerCase(),
+ settings = V2rayConfig.OutboundBean.OutSettingsBean(
+ servers = listOf(V2rayConfig.OutboundBean.OutSettingsBean.ServersBean())),
+ streamSettings = V2rayConfig.OutboundBean.StreamSettingsBean()))
+ }
+ }
+ }
+
+ fun getProxyOutbound(): V2rayConfig.OutboundBean? {
+ if (configType != EConfigType.CUSTOM) {
+ return outboundBean
+ }
+ return fullConfig?.getProxyOutbound()
+ }
+
+ fun getAllOutboundTags(): MutableList {
+ if (configType != EConfigType.CUSTOM) {
+ return mutableListOf(TAG_AGENT, TAG_DIRECT, TAG_BLOCKED)
+ }
+ fullConfig?.let { config ->
+ return config.outbounds.map { it.tag }.toMutableList()
+ }
+ return mutableListOf()
+ }
+
+ fun getV2rayPointDomainAndPort(): String {
+ val address = getProxyOutbound()?.getServerAddress().orEmpty()
+ val port = getProxyOutbound()?.getServerPort()
+ return if (Utils.isIpv6Address(address)) {
+ String.format("[%s]:%s", address, port)
+ } else {
+ String.format("%s:%s", address, port)
+ }
+ }
+}
diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/SubscriptionItem.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/SubscriptionItem.kt
new file mode 100644
index 00000000..b2195148
--- /dev/null
+++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/SubscriptionItem.kt
@@ -0,0 +1,8 @@
+package com.v2ray.ang.dto
+
+data class SubscriptionItem(
+ var remarks: String = "",
+ var url: String = "",
+ var enabled: Boolean = true,
+ val addedTime: Long = System.currentTimeMillis()) {
+}
diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/V2rayConfig.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/V2rayConfig.kt
index 57fd191f..76e410cb 100644
--- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/V2rayConfig.kt
+++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/V2rayConfig.kt
@@ -1,91 +1,149 @@
package com.v2ray.ang.dto
+import android.text.TextUtils
+import com.google.gson.GsonBuilder
+import com.google.gson.JsonPrimitive
+import com.google.gson.JsonSerializationContext
+import com.google.gson.JsonSerializer
+import com.google.gson.reflect.TypeToken
+import java.lang.reflect.Type
+
data class V2rayConfig(
- val stats: Any?=null,
+ var stats: Any? = null,
val log: LogBean,
- val policy: PolicyBean,
+ var policy: PolicyBean?,
val inbounds: ArrayList,
var outbounds: ArrayList,
var dns: DnsBean,
- val routing: RoutingBean) {
+ val routing: RoutingBean,
+ val api: Any? = null,
+ val transport: Any? = null,
+ val reverse: Any? = null,
+ val fakedns: Any? = null) {
+ companion object {
+ const val DEFAULT_PORT = 443
+ const val DEFAULT_SECURITY = "auto"
+ const val DEFAULT_LEVEL = 8
+ const val DEFAULT_NETWORK = "tcp"
+ const val DEFAULT_FLOW = "xtls-rprx-splice"
+
+ const val TLS = "tls"
+ const val XTLS = "xtls"
+ const val HTTP = "http"
+ }
data class LogBean(val access: String,
val error: String,
- val loglevel: String)
+ var loglevel: String?)
data class InboundBean(
var tag: String,
var port: Int,
var protocol: String,
- var listen: String?=null,
- val settings: InSettingsBean,
- val sniffing: SniffingBean?) {
+ var listen: String? = null,
+ val settings: Any? = null,
+ val sniffing: SniffingBean?,
+ val streamSettings: Any? = null,
+ val allocate: Any? = null) {
data class InSettingsBean(val auth: String? = null,
val udp: Boolean? = null,
- val userLevel: Int? =null,
+ val userLevel: Int? = null,
val address: String? = null,
val port: Int? = null,
val network: String? = null)
data class SniffingBean(var enabled: Boolean,
- val destOverride: List)
+ val destOverride: List,
+ val metadataOnly: Boolean? = null)
}
- data class OutboundBean(val tag: String,
+ data class OutboundBean(val tag: String = "proxy",
var protocol: String,
- var settings: OutSettingsBean?,
- var streamSettings: StreamSettingsBean?,
- var mux: MuxBean?) {
+ var settings: OutSettingsBean? = null,
+ var streamSettings: StreamSettingsBean? = null,
+ val proxySettings: Any? = null,
+ val sendThrough: String? = null,
+ val mux: MuxBean? = MuxBean(false)) {
- data class OutSettingsBean(var vnext: List?,
- var servers: List?,
- var response: Response) {
+ data class OutSettingsBean(var vnext: List? = null,
+ var servers: List? = null,
+ /*Blackhole*/
+ var response: Response? = null,
+ /*DNS*/
+ val network: String? = null,
+ val address: String? = null,
+ val port: Int? = null,
+ /*Freedom*/
+ val domainStrategy: String? = null,
+ val redirect: String? = null,
+ val userLevel: Int? = null,
+ /*Loopback*/
+ val inboundTag: String? = null) {
- data class VnextBean(var address: String,
- var port: Int,
+ data class VnextBean(var address: String = "",
+ var port: Int = DEFAULT_PORT,
var users: List) {
- data class UsersBean(var id: String,
- var alterId: Int,
- var security: String,
- var level: Int)
+ data class UsersBean(var id: String = "",
+ var alterId: Int? = null,
+ var security: String = DEFAULT_SECURITY,
+ var level: Int = DEFAULT_LEVEL,
+ var encryption: String = "",
+ var flow: String = "")
}
- data class ServersBean(var address: String,
- var method: String,
- var ota: Boolean,
- var password: String,
- var port: Int,
- var level: Int)
+ data class ServersBean(var address: String = "",
+ var method: String = "chacha20-poly1305",
+ var ota: Boolean = false,
+ var password: String = "",
+ var port: Int = DEFAULT_PORT,
+ var level: Int = DEFAULT_LEVEL,
+ var users: List? = null) {
+
+
+ data class SocksUsersBean(var user: String = "",
+ var pass: String = "",
+ var level: Int = DEFAULT_LEVEL)
+ }
data class Response(var type: String)
}
- data class StreamSettingsBean(var network: String,
- var security: String,
- var tcpSettings: TcpSettingsBean?,
- var kcpSettings: KcpSettingsBean?,
- var wsSettings: WsSettingsBean?,
- var httpSettings: HttpSettingsBean?,
- var tlsSettings: TlsSettingsBean?,
- var quicSettings: QuicSettingBean?
+ data class StreamSettingsBean(var network: String = DEFAULT_NETWORK,
+ var security: String = "",
+ var tcpSettings: TcpSettingsBean? = null,
+ var kcpSettings: KcpSettingsBean? = null,
+ var wsSettings: WsSettingsBean? = null,
+ var httpSettings: HttpSettingsBean? = null,
+ var tlsSettings: TlsSettingsBean? = null,
+ var quicSettings: QuicSettingBean? = null,
+ var xtlsSettings: TlsSettingsBean? = null,
+ val grpcSettings: Any? = null,
+ val dsSettings: Any? = null,
+ val sockopt: Any? = null
) {
data class TcpSettingsBean(var header: HeaderBean = HeaderBean()) {
data class HeaderBean(var type: String = "none",
- var request: Any? = null,
- var response: Any? = null)
+ var request: RequestBean? = null,
+ var response: Any? = null) {
+ data class RequestBean(var path: List = ArrayList(),
+ var headers: HeadersBean = HeadersBean()) {
+ data class HeadersBean(var Host: List = ArrayList())
+ }
+ }
}
data class KcpSettingsBean(var mtu: Int = 1350,
- var tti: Int = 20,
+ var tti: Int = 50,
var uplinkCapacity: Int = 12,
var downlinkCapacity: Int = 100,
var congestion: Boolean = false,
var readBufferSize: Int = 1,
var writeBufferSize: Int = 1,
- var header: HeaderBean = HeaderBean()) {
+ var header: HeaderBean = HeaderBean(),
+ var seed: String? = null) {
data class HeaderBean(var type: String = "none")
}
@@ -97,63 +155,243 @@ data class V2rayConfig(
data class HttpSettingsBean(var host: List = ArrayList(),
var path: String = "")
- data class TlsSettingsBean(var allowInsecure: Boolean = true,
- var serverName: String = "")
+ data class TlsSettingsBean(var allowInsecure: Boolean = false,
+ var serverName: String = "",
+ val alpn: List? = null,
+ val certificates: List? = null,
+ val disableSystemRoot: Boolean? = null)
data class QuicSettingBean(var security: String = "none",
var key: String = "",
var header: HeaderBean = HeaderBean()) {
data class HeaderBean(var type: String = "none")
}
+
+ fun populateTransportSettings(transport: String, headerType: String?, host: String?, path: String?, seed: String?,
+ quicSecurity: String?, key: String?): String {
+ var sni = ""
+ network = transport
+ when (network) {
+ "tcp" -> if (headerType == HTTP) {
+ val tcpSetting = TcpSettingsBean()
+ tcpSetting.header.type = HTTP
+ if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(path)) {
+ val requestObj = TcpSettingsBean.HeaderBean.RequestBean()
+ requestObj.headers.Host = (host ?: "").split(",").map { it.trim() }
+ requestObj.path = (path ?: "").split(",").map { it.trim() }
+ tcpSetting.header.request = requestObj
+ sni = requestObj.headers.Host.getOrNull(0) ?: sni
+ }
+ tcpSettings = tcpSetting
+ }
+ "kcp" -> {
+ val kcpsetting = KcpSettingsBean()
+ kcpsetting.header.type = headerType ?: "none"
+ if (seed.isNullOrEmpty()) {
+ kcpsetting.seed = null
+ } else {
+ kcpsetting.seed = seed
+ }
+ kcpSettings = kcpsetting
+ }
+ "ws" -> {
+ val wssetting = WsSettingsBean()
+ wssetting.headers.Host = host ?: ""
+ sni = wssetting.headers.Host
+ wssetting.path = path ?: "/"
+ wsSettings = wssetting
+ }
+ "h2", "http" -> {
+ network = "h2"
+ val h2Setting = HttpSettingsBean()
+ h2Setting.host = (host ?: "").split(",").map { it.trim() }
+ sni = h2Setting.host.getOrNull(0) ?: sni
+ h2Setting.path = path ?: "/"
+ httpSettings = h2Setting
+ }
+ "quic" -> {
+ val quicsetting = QuicSettingBean()
+ quicsetting.security = quicSecurity ?: "none"
+ quicsetting.key = key ?: ""
+ quicsetting.header.type = headerType ?: "none"
+ quicSettings = quicsetting
+ }
+ }
+ return sni
+ }
+
+ fun populateTlsSettings(streamSecurity: String, allowInsecure: Boolean, sni: String) {
+ security = streamSecurity
+ val tlsSetting = TlsSettingsBean(
+ allowInsecure = allowInsecure,
+ serverName = sni
+ )
+ if (security == TLS) {
+ tlsSettings = tlsSetting
+ } else if (security == XTLS) {
+ xtlsSettings = tlsSetting
+ }
+ }
}
- data class MuxBean(var enabled: Boolean)
+ data class MuxBean(var enabled: Boolean, var concurrency: Int = 8)
fun getServerAddress(): String? {
- if (protocol.equals(EConfigType.VMESS.name.toLowerCase())) {
+ if (protocol.equals(EConfigType.VMESS.name, true)
+ || protocol.equals(EConfigType.VLESS.name, true)) {
return settings?.vnext?.get(0)?.address
- } else if (protocol.equals(EConfigType.SHADOWSOCKS.name.toLowerCase()) || protocol.equals(EConfigType.SOCKS.name.toLowerCase())) {
+ } else if (protocol.equals(EConfigType.SHADOWSOCKS.name, true)
+ || protocol.equals(EConfigType.SOCKS.name, true)
+ || protocol.equals(EConfigType.TROJAN.name, true)) {
return settings?.servers?.get(0)?.address
}
return null
}
fun getServerPort(): Int? {
- if (protocol.equals(EConfigType.VMESS.name.toLowerCase())) {
+ if (protocol.equals(EConfigType.VMESS.name, true)
+ || protocol.equals(EConfigType.VLESS.name, true)) {
return settings?.vnext?.get(0)?.port
- } else if (protocol.equals(EConfigType.SHADOWSOCKS.name.toLowerCase()) || protocol.equals(EConfigType.SOCKS.name.toLowerCase())) {
+ } else if (protocol.equals(EConfigType.SHADOWSOCKS.name, true)
+ || protocol.equals(EConfigType.SOCKS.name, true)
+ || protocol.equals(EConfigType.TROJAN.name, true)) {
return settings?.servers?.get(0)?.port
}
return null
}
+
+ fun getPassword(): String? {
+ if (protocol.equals(EConfigType.VMESS.name, true)
+ || protocol.equals(EConfigType.VLESS.name, true)) {
+ return settings?.vnext?.get(0)?.users?.get(0)?.id
+ } else if (protocol.equals(EConfigType.SHADOWSOCKS.name, true)
+ || protocol.equals(EConfigType.TROJAN.name, true)) {
+ return settings?.servers?.get(0)?.password
+ } else if (protocol.equals(EConfigType.SOCKS.name, true)) {
+ return settings?.servers?.get(0)?.users?.get(0)?.pass
+ }
+ return null
+ }
+
+ fun getSecurityEncryption(): String? {
+ return when {
+ protocol.equals(EConfigType.VMESS.name, true) -> settings?.vnext?.get(0)?.users?.get(0)?.security
+ protocol.equals(EConfigType.VLESS.name, true) -> settings?.vnext?.get(0)?.users?.get(0)?.encryption
+ protocol.equals(EConfigType.SHADOWSOCKS.name, true) -> settings?.servers?.get(0)?.method
+ else -> null
+ }
+ }
+
+ fun getTransportSettingDetails(): List? {
+ if (protocol.equals(EConfigType.VMESS.name, true)
+ || protocol.equals(EConfigType.VLESS.name, true)) {
+ val transport = streamSettings?.network ?: return null
+ return when(transport) {
+ "tcp" -> {
+ val tcpSetting = streamSettings?.tcpSettings ?: return null
+ listOf(tcpSetting.header.type,
+ tcpSetting.header.request?.headers?.Host?.joinToString().orEmpty(),
+ tcpSetting.header.request?.path?.joinToString().orEmpty())
+ }
+ "kcp" -> {
+ val kcpSetting = streamSettings?.kcpSettings ?: return null
+ listOf(kcpSetting.header.type,
+ "",
+ kcpSetting.seed.orEmpty())
+ }
+ "ws" -> {
+ val wsSetting = streamSettings?.wsSettings ?: return null
+ listOf("",
+ wsSetting.headers.Host,
+ wsSetting.path)
+ }
+ "h2" -> {
+ val h2Setting = streamSettings?.httpSettings ?: return null
+ listOf("",
+ h2Setting.host.joinToString(),
+ h2Setting.path)
+ }
+ "quic" -> {
+ val quicSetting = streamSettings?.quicSettings ?: return null
+ listOf(quicSetting.header.type,
+ quicSetting.security,
+ quicSetting.key)
+ }
+ else -> null
+ }
+ }
+ return null
+ }
}
- //data class DnsBean(var servers: List)
- data class DnsBean(var servers: List?=null,
- var hosts: Map?=null
+ data class DnsBean(var servers: List? = null,
+ var hosts: Map? = null,
+ val clientIp: String? = null,
+ val disableCache: Boolean? = null,
+ val tag: String? = null
) {
data class ServersBean(var address: String = "",
var port: Int = 0,
- var domains: List?)
+ var domains: List?,
+ var expectIPs: List?,
+ val clientIp: String? = null)
}
data class RoutingBean(var domainStrategy: String,
- var rules: ArrayList) {
+ val domainMatcher: String? = null,
+ var rules: ArrayList,
+ val balancers: List? = null) {
data class RulesBean(var type: String = "",
var ip: ArrayList? = null,
var domain: ArrayList? = null,
var outboundTag: String = "",
+ var balancerTag: String? = null,
var port: String? = null,
- var inboundTag: ArrayList? = null)
+ val sourcePort: String? = null,
+ val network: String? = null,
+ val source: List? = null,
+ val user: List? = null,
+ var inboundTag: List? = null,
+ val protocol: List? = null,
+ val attrs: String? = null,
+ val domainMatcher: String? = null
+ )
}
data class PolicyBean(var levels: Map,
- var system: Any?=null) {
+ var system: Any? = null) {
data class LevelBean(
- var handshake: Int? = null,
- var connIdle: Int? = null,
- var uplinkOnly: Int? = null,
- var downlinkOnly: Int? = null)
+ var handshake: Int? = null,
+ var connIdle: Int? = null,
+ var uplinkOnly: Int? = null,
+ var downlinkOnly: Int? = null,
+ val statsUserUplink: Boolean? = null,
+ val statsUserDownlink: Boolean? = null,
+ var bufferSize: Int? = null)
}
-}
\ No newline at end of file
+
+ fun getProxyOutbound(): OutboundBean? {
+ outbounds.forEach { outbound ->
+ if (outbound.protocol.equals(EConfigType.VMESS.name, true) ||
+ outbound.protocol.equals(EConfigType.VLESS.name, true) ||
+ outbound.protocol.equals(EConfigType.SHADOWSOCKS.name, true) ||
+ outbound.protocol.equals(EConfigType.SOCKS.name, true) ||
+ outbound.protocol.equals(EConfigType.TROJAN.name, true)) {
+ return outbound
+ }
+ }
+ return null
+ }
+
+ fun toPrettyPrinting(): String {
+ return GsonBuilder()
+ .setPrettyPrinting()
+ .registerTypeAdapter( // custom serialiser is needed here since JSON by default parse number as Double, core will fail to start
+ object: TypeToken() {}.type,
+ JsonSerializer { src: Double?, _: Type?, _: JsonSerializationContext? -> JsonPrimitive(src?.toInt()) }
+ )
+ .create()
+ .toJson(this)
+ }
+}
diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/VmessQRCode.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/VmessQRCode.kt
index 30618017..d8363ca5 100644
--- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/VmessQRCode.kt
+++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/dto/VmessQRCode.kt
@@ -10,4 +10,5 @@ data class VmessQRCode(var v: String = "",
var type: String = "",
var host: String = "",
var path: String = "",
- var tls: String = "")
\ No newline at end of file
+ var tls: String = "",
+ var sni: String = "")
diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Ext.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Ext.kt
index 73a400cd..4d317e67 100644
--- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Ext.kt
+++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Ext.kt
@@ -4,7 +4,6 @@ import android.content.Context
import android.os.Build
import android.widget.Toast
import com.v2ray.ang.AngApplication
-import me.dozen.dpreference.DPreference
import me.drakeet.support.toast.ToastCompat
import org.json.JSONObject
import java.net.URLConnection
@@ -16,13 +15,6 @@ import java.net.URLConnection
val Context.v2RayApplication: AngApplication
get() = applicationContext as AngApplication
-// Usage note: DPreference use Android ContentProvider to redirect multi process access to main process.
-// Currently, RunSoLibV2RayDaemon process will run proxy core, keep minimum configuration and long running
-// in the background, support toggle on/off. That means it should NOT use DPreference after the initial
-// creation and setup of the service
-val Context.defaultDPreference: DPreference
- get() = v2RayApplication.defaultDPreference
-
inline fun Context.toast(message: Int): Toast = ToastCompat
.makeText(this, message, Toast.LENGTH_SHORT)
.apply {
@@ -35,7 +27,7 @@ inline fun Context.toast(message: CharSequence): Toast = ToastCompat
show()
}
-fun JSONObject.putOpt(pair: Pair) = putOpt(pair.first, pair.second)!!
+fun JSONObject.putOpt(pair: Pair) = putOpt(pair.first, pair.second)
fun JSONObject.putOpt(pairs: Map) = pairs.forEach { putOpt(it.key to it.value) }
const val threshold = 1000
diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Preference.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Preference.kt
deleted file mode 100644
index dcfa4671..00000000
--- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/extension/_Preference.kt
+++ /dev/null
@@ -1,10 +0,0 @@
-package com.v2ray.ang.extension
-
-import android.preference.Preference
-
-fun Preference.onClick(listener: () -> Unit) {
- setOnPreferenceClickListener {
- listener()
- true
- }
-}
\ No newline at end of file
diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/receiver/TaskerReceiver.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/receiver/TaskerReceiver.kt
index 74f69416..08a3184a 100644
--- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/receiver/TaskerReceiver.kt
+++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/receiver/TaskerReceiver.kt
@@ -5,11 +5,16 @@ import android.content.Context
import android.content.Intent
import android.text.TextUtils
import com.google.zxing.WriterException
+import com.tencent.mmkv.MMKV
import com.v2ray.ang.AppConfig
+import com.v2ray.ang.service.V2RayServiceManager
+import com.v2ray.ang.util.MmkvManager
import com.v2ray.ang.util.Utils
class TaskerReceiver : BroadcastReceiver() {
+ private val mainStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_MAIN, MMKV.MULTI_PROCESS_MODE) }
+
override fun onReceive(context: Context, intent: Intent?) {
try {
@@ -23,7 +28,8 @@ class TaskerReceiver : BroadcastReceiver() {
if (guid == AppConfig.TASKER_DEFAULT_GUID) {
Utils.startVServiceFromToggle(context)
} else {
- Utils.startVService(context, guid)
+ mainStorage?.encode(MmkvManager.KEY_SELECTED_SERVER, guid)
+ V2RayServiceManager.startV2Ray(context)
}
} else {
Utils.stopVService(context)
diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/QSTileService.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/QSTileService.kt
index 72994f10..b7e07e91 100644
--- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/QSTileService.kt
+++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/QSTileService.kt
@@ -25,7 +25,7 @@ class QSTileService : TileService() {
qsTile?.icon = Icon.createWithResource(applicationContext, R.drawable.ic_v_idle)
} else if (state == Tile.STATE_ACTIVE) {
qsTile?.state = Tile.STATE_ACTIVE
- qsTile?.label = V2RayServiceManager.currentConfigName
+ qsTile?.label = V2RayServiceManager.currentConfig?.remarks
qsTile?.icon = Icon.createWithResource(applicationContext, R.drawable.ic_v)
}
diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayServiceManager.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayServiceManager.kt
index 86e8ff05..1387439f 100644
--- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayServiceManager.kt
+++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayServiceManager.kt
@@ -13,17 +13,18 @@ import android.os.Build
import android.support.annotation.RequiresApi
import android.support.v4.app.NotificationCompat
import android.util.Log
+import com.tencent.mmkv.MMKV
import com.v2ray.ang.AppConfig
import com.v2ray.ang.AppConfig.TAG_DIRECT
import com.v2ray.ang.R
-import com.v2ray.ang.extension.defaultDPreference
+import com.v2ray.ang.dto.ServerConfig
import com.v2ray.ang.extension.toSpeedString
import com.v2ray.ang.extension.toast
-import com.v2ray.ang.extension.v2RayApplication
import com.v2ray.ang.ui.MainActivity
-import com.v2ray.ang.ui.SettingsActivity
import com.v2ray.ang.util.MessageUtil
+import com.v2ray.ang.util.MmkvManager
import com.v2ray.ang.util.Utils
+import com.v2ray.ang.util.V2rayConfigUtil
import go.Seq
import libv2ray.Libv2ray
import libv2ray.V2RayPoint
@@ -41,6 +42,8 @@ object V2RayServiceManager {
val v2rayPoint: V2RayPoint = Libv2ray.newV2RayPoint(V2RayCallback())
private val mMsgReceive = ReceiveMessageHandler()
+ private val mainStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_MAIN, MMKV.MULTI_PROCESS_MODE) }
+ private val settingsStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_SETTING, MMKV.MULTI_PROCESS_MODE) }
var serviceControl: SoftReference? = null
set(value) {
@@ -52,7 +55,7 @@ object V2RayServiceManager {
Seq.setContext(context)
}
}
- var currentConfigName = "NG"
+ var currentConfig: ServerConfig? = null
private var lastQueryTime = 0L
private var mBuilder: NotificationCompat.Builder? = null
@@ -60,12 +63,12 @@ object V2RayServiceManager {
private var mNotificationManager: NotificationManager? = null
fun startV2Ray(context: Context) {
- if (context.v2RayApplication.defaultDPreference.getPrefBoolean(SettingsActivity.PREF_PROXY_SHARING, false)) {
+ if (settingsStorage?.decodeBool(AppConfig.PREF_PROXY_SHARING) == true) {
context.toast(R.string.toast_warning_pref_proxysharing_short)
}else{
context.toast(R.string.toast_services_start)
}
- val intent = if (context.v2RayApplication.defaultDPreference.getPrefString(AppConfig.PREF_MODE, "VPN") == "VPN") {
+ val intent = if (settingsStorage?.decodeString(AppConfig.PREF_MODE) ?: "VPN" == "VPN") {
Intent(context.applicationContext, V2RayVpnService::class.java)
} else {
Intent(context.applicationContext, V2RayProxyOnlyService::class.java)
@@ -123,7 +126,12 @@ object V2RayServiceManager {
fun startV2rayPoint() {
val service = serviceControl?.get()?.getService() ?: return
+ val guid = mainStorage?.decodeString(MmkvManager.KEY_SELECTED_SERVER) ?: return
+ val config = MmkvManager.decodeServerConfig(guid) ?: return
if (!v2rayPoint.isRunning) {
+ val result = V2rayConfigUtil.getV2rayConfig(service, guid)
+ if (!result.status)
+ return
try {
val mFilter = IntentFilter(AppConfig.BROADCAST_ACTION_SERVICE)
@@ -135,12 +143,12 @@ object V2RayServiceManager {
Log.d(service.packageName, e.toString())
}
- v2rayPoint.configureFileContent = service.defaultDPreference.getPrefString(AppConfig.PREF_CURR_CONFIG, "")
- v2rayPoint.enableLocalDNS = service.defaultDPreference.getPrefBoolean(SettingsActivity.PREF_LOCAL_DNS_ENABLED, false)
- v2rayPoint.forwardIpv6 = service.defaultDPreference.getPrefBoolean(SettingsActivity.PREF_FORWARD_IPV6, false)
- v2rayPoint.domainName = service.defaultDPreference.getPrefString(AppConfig.PREF_CURR_CONFIG_DOMAIN, "")
- v2rayPoint.proxyOnly = service.defaultDPreference.getPrefString(AppConfig.PREF_MODE, "VPN") != "VPN"
- currentConfigName = service.defaultDPreference.getPrefString(AppConfig.PREF_CURR_CONFIG_NAME, "NG")
+ v2rayPoint.configureFileContent = result.content
+ v2rayPoint.domainName = config.getV2rayPointDomainAndPort()
+ currentConfig = config
+ v2rayPoint.enableLocalDNS = settingsStorage?.decodeBool(AppConfig.PREF_LOCAL_DNS_ENABLED) ?: false
+ v2rayPoint.forwardIpv6 = settingsStorage?.decodeBool(AppConfig.PREF_FORWARD_IPV6) ?: false
+ v2rayPoint.proxyOnly = settingsStorage?.decodeString(AppConfig.PREF_MODE) ?: "VPN" != "VPN"
try {
v2rayPoint.runLoop()
@@ -244,7 +252,7 @@ object V2RayServiceManager {
mBuilder = NotificationCompat.Builder(service, channelId)
.setSmallIcon(R.drawable.ic_v)
- .setContentTitle(currentConfigName)
+ .setContentTitle(currentConfig?.remarks)
.setPriority(NotificationCompat.PRIORITY_MIN)
.setOngoing(true)
.setShowWhen(false)
@@ -281,7 +289,7 @@ object V2RayServiceManager {
mSubscription = null
}
- private fun updateNotification(contentText: String, proxyTraffic: Long, directTraffic: Long) {
+ private fun updateNotification(contentText: String?, proxyTraffic: Long, directTraffic: Long) {
if (mBuilder != null) {
if (proxyTraffic < NOTIFICATION_ICON_THRESHOLD && directTraffic < NOTIFICATION_ICON_THRESHOLD) {
mBuilder?.setSmallIcon(R.drawable.ic_v)
@@ -305,13 +313,12 @@ object V2RayServiceManager {
}
fun startSpeedNotification() {
- val service = serviceControl?.get()?.getService() ?: return
if (mSubscription == null &&
v2rayPoint.isRunning &&
- service.defaultDPreference.getPrefBoolean(SettingsActivity.PREF_SPEED_ENABLED, false)) {
+ settingsStorage?.decodeBool(AppConfig.PREF_SPEED_ENABLED) == true) {
var lastZeroSpeed = false
- val outboundTags = service.defaultDPreference.getPrefStringOrderedSet(AppConfig.PREF_CURR_CONFIG_OUTBOUND_TAGS, LinkedHashSet())
- outboundTags.remove(TAG_DIRECT)
+ val outboundTags = currentConfig?.getAllOutboundTags()
+ outboundTags?.remove(TAG_DIRECT)
mSubscription = Observable.interval(3, java.util.concurrent.TimeUnit.SECONDS)
.subscribe {
@@ -319,7 +326,7 @@ object V2RayServiceManager {
val sinceLastQueryInSeconds = (queryTime - lastQueryTime) / 1000.0
var proxyTotal = 0L
val text = StringBuilder()
- outboundTags.forEach {
+ outboundTags?.forEach {
val up = v2rayPoint.queryStats(it, "uplink")
val down = v2rayPoint.queryStats(it, "downlink")
if (up + down > 0) {
@@ -332,7 +339,7 @@ object V2RayServiceManager {
val zeroSpeed = (proxyTotal == 0L && directUplink == 0L && directDownlink == 0L)
if (!zeroSpeed || !lastZeroSpeed) {
if (proxyTotal == 0L) {
- appendSpeedString(text, outboundTags.firstOrNull(), 0.0, 0.0)
+ appendSpeedString(text, outboundTags?.firstOrNull(), 0.0, 0.0)
}
appendSpeedString(text, TAG_DIRECT, directUplink / sinceLastQueryInSeconds,
directDownlink / sinceLastQueryInSeconds)
@@ -358,7 +365,7 @@ object V2RayServiceManager {
if (mSubscription != null) {
mSubscription?.unsubscribe() //stop queryStats
mSubscription = null
- updateNotification(currentConfigName, 0, 0)
+ updateNotification(currentConfig?.remarks, 0, 0)
}
}
}
diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayVpnService.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayVpnService.kt
index 7339f9fe..efc410ff 100644
--- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayVpnService.kt
+++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/service/V2RayVpnService.kt
@@ -10,10 +10,10 @@ import android.os.ParcelFileDescriptor
import android.os.StrictMode
import android.support.annotation.RequiresApi
import android.util.Log
+import com.tencent.mmkv.MMKV
+import com.v2ray.ang.AppConfig
import com.v2ray.ang.R
-import com.v2ray.ang.extension.defaultDPreference
-import com.v2ray.ang.ui.PerAppProxyActivity
-import com.v2ray.ang.ui.SettingsActivity
+import com.v2ray.ang.util.MmkvManager
import com.v2ray.ang.util.Utils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
@@ -22,6 +22,8 @@ import java.io.File
import java.lang.ref.SoftReference
class V2RayVpnService : VpnService(), ServiceControl {
+ private val settingsStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_SETTING, MMKV.MULTI_PROCESS_MODE) }
+
private lateinit var mInterface: ParcelFileDescriptor
/**
@@ -91,8 +93,8 @@ class V2RayVpnService : VpnService(), ServiceControl {
// If the old interface has exactly the same parameters, use it!
// Configure a builder while parsing the parameters.
val builder = Builder()
- val enableLocalDns = defaultDPreference.getPrefBoolean(SettingsActivity.PREF_LOCAL_DNS_ENABLED, false)
- val routingMode = defaultDPreference.getPrefString(SettingsActivity.PREF_ROUTING_MODE, "0")
+ val enableLocalDns = settingsStorage?.decodeBool(AppConfig.PREF_LOCAL_DNS_ENABLED) ?: false
+ val routingMode = settingsStorage?.decodeString(AppConfig.PREF_ROUTING_MODE) ?: "0"
parameters.split(" ")
.map { it.split(",") }
@@ -120,18 +122,18 @@ class V2RayVpnService : VpnService(), ServiceControl {
}
if(!enableLocalDns) {
- Utils.getRemoteDnsServers(defaultDPreference)
+ Utils.getRemoteDnsServers()
.forEach {
builder.addDnsServer(it)
}
}
- builder.setSession(V2RayServiceManager.currentConfigName)
+ builder.setSession(V2RayServiceManager.currentConfig?.remarks.orEmpty())
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP &&
- defaultDPreference.getPrefBoolean(SettingsActivity.PREF_PER_APP_PROXY, false)) {
- val apps = defaultDPreference.getPrefStringSet(PerAppProxyActivity.PREF_PER_APP_PROXY_SET, null)
- val bypassApps = defaultDPreference.getPrefBoolean(PerAppProxyActivity.PREF_BYPASS_APPS, false)
+ settingsStorage?.decodeBool(AppConfig.PREF_PER_APP_PROXY) == true) {
+ val apps = settingsStorage?.decodeStringSet(AppConfig.PREF_PER_APP_PROXY_SET)
+ val bypassApps = settingsStorage?.decodeBool(AppConfig.PREF_BYPASS_APPS) ?: false
apps?.forEach {
try {
if (bypassApps)
diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/BaseDrawerActivity.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/BaseDrawerActivity.kt
deleted file mode 100644
index 231575bb..00000000
--- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/BaseDrawerActivity.kt
+++ /dev/null
@@ -1,199 +0,0 @@
-package com.v2ray.ang.ui
-
-import android.app.ActivityOptions
-import android.app.FragmentManager
-import android.content.Intent
-import android.content.res.Configuration
-import android.os.Bundle
-import android.support.design.widget.NavigationView
-import android.support.v4.view.GravityCompat
-import android.support.v4.widget.DrawerLayout
-import android.support.v7.app.ActionBarDrawerToggle
-import android.support.v7.widget.Toolbar
-import android.util.Log
-import android.view.MenuItem
-import android.view.View
-import com.v2ray.ang.R
-
-abstract class BaseDrawerActivity : BaseActivity() {
- companion object {
-
- private val TAG = "BaseDrawerActivity"
- }
-
- private var mToolbar: Toolbar? = null
-
- private var mDrawerToggle: ActionBarDrawerToggle? = null
-
- private var mDrawerLayout: DrawerLayout? = null
-
- private var mToolbarInitialized: Boolean = false
-
- private var mItemToOpenWhenDrawerCloses = -1
-
- private val backStackChangedListener = FragmentManager.OnBackStackChangedListener { updateDrawerToggle() }
-
- private val drawerListener = object : DrawerLayout.DrawerListener {
- override fun onDrawerSlide(drawerView: View, slideOffset: Float) {
- mDrawerToggle!!.onDrawerSlide(drawerView, slideOffset)
- }
-
- override fun onDrawerOpened(drawerView: View) {
- mDrawerToggle!!.onDrawerOpened(drawerView)
- //supportActionBar!!.setTitle(R.string.app_name)
- }
-
- override fun onDrawerClosed(drawerView: View) {
- mDrawerToggle!!.onDrawerClosed(drawerView)
-
- if (mItemToOpenWhenDrawerCloses >= 0) {
- val extras = ActivityOptions.makeCustomAnimation(
- this@BaseDrawerActivity, R.anim.fade_in, R.anim.fade_out).toBundle()
- var activityClass: Class<*>? = null
- when (mItemToOpenWhenDrawerCloses) {
- R.id.sub_setting -> activityClass = SubSettingActivity::class.java
- R.id.settings -> activityClass = SettingsActivity::class.java
- R.id.logcat -> {
- startActivity(Intent(this@BaseDrawerActivity, LogcatActivity::class.java))
- return
- }
- R.id.donate -> {
-// startActivity()
- return
- }
- }
- if (activityClass != null) {
- startActivity(Intent(this@BaseDrawerActivity, activityClass), extras)
- finish()
- }
- }
- }
-
- override fun onDrawerStateChanged(newState: Int) {
- mDrawerToggle!!.onDrawerStateChanged(newState)
- }
- }
-
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- Log.d(TAG, "Activity onCreate")
- }
-
- override fun onStart() {
- super.onStart()
- if (!mToolbarInitialized) {
- throw IllegalStateException("You must run super.initializeToolbar at " + "the end of your onCreate method")
- }
- }
-
- public override fun onResume() {
- super.onResume()
- // Whenever the fragment back stack changes, we may need to update the
- // action bar toggle: only top level screens show the hamburger-like icon, inner
- // screens - either Activities or fragments - show the "Up" icon instead.
- fragmentManager.addOnBackStackChangedListener(backStackChangedListener)
- }
-
- public override fun onPause() {
- super.onPause()
- fragmentManager.removeOnBackStackChangedListener(backStackChangedListener)
- }
-
- override fun onPostCreate(savedInstanceState: Bundle?) {
- super.onPostCreate(savedInstanceState)
- mDrawerToggle!!.syncState()
- }
-
- override fun onConfigurationChanged(newConfig: Configuration) {
- super.onConfigurationChanged(newConfig)
- mDrawerToggle!!.onConfigurationChanged(newConfig)
- }
-
- override fun onOptionsItemSelected(item: MenuItem): Boolean {
- if (mDrawerToggle != null && mDrawerToggle!!.onOptionsItemSelected(item)) {
- return true
- }
- // If not handled by drawerToggle, home needs to be handled by returning to previous
- if (item.itemId == android.R.id.home) {
- onBackPressed()
- return true
- }
- return super.onOptionsItemSelected(item)
- }
-
- override fun onBackPressed() {
- // If the drawer is open, back will close it
- if (mDrawerLayout != null && mDrawerLayout!!.isDrawerOpen(GravityCompat.START)) {
- mDrawerLayout!!.closeDrawers()
- return
- }
- // Otherwise, it may return to the previous fragment stack
- val fragmentManager = fragmentManager
- if (fragmentManager.backStackEntryCount > 0) {
- fragmentManager.popBackStack()
- } else {
- // Lastly, it will rely on the system behavior for back
- super.onBackPressed()
- }
- }
-
- private fun updateDrawerToggle() {
- if (mDrawerToggle == null) {
- return
- }
- val isRoot = fragmentManager.backStackEntryCount == 0
- mDrawerToggle!!.isDrawerIndicatorEnabled = isRoot
-
- supportActionBar!!.setDisplayShowHomeEnabled(!isRoot)
- supportActionBar!!.setDisplayHomeAsUpEnabled(!isRoot)
- supportActionBar!!.setHomeButtonEnabled(!isRoot)
-
- if (isRoot) {
- mDrawerToggle!!.syncState()
- }
- }
-
- protected fun initializeToolbar() {
- mToolbar = findViewById(R.id.toolbar) as Toolbar
- if (mToolbar == null) {
- throw IllegalStateException("Layout is required to include a Toolbar with id " + "'toolbar'")
- }
-
- // mToolbar.inflateMenu(R.menu.main);
-
- mDrawerLayout = findViewById(R.id.drawer_layout) as DrawerLayout
- if (mDrawerLayout != null) {
- val navigationView = findViewById(R.id.nav_view) as NavigationView
- ?: throw IllegalStateException("Layout requires a NavigationView " + "with id 'nav_view'")
-
- // Create an ActionBarDrawerToggle that will handle opening/closing of the drawer:
- mDrawerToggle = ActionBarDrawerToggle(this, mDrawerLayout,
- mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
-
- mDrawerLayout!!.addDrawerListener(drawerListener)
-
- populateDrawerItems(navigationView)
- setSupportActionBar(mToolbar)
- updateDrawerToggle()
- } else {
- setSupportActionBar(mToolbar)
- }
-
- mToolbarInitialized = true
- }
-
- private fun populateDrawerItems(navigationView: NavigationView) {
- navigationView.setNavigationItemSelectedListener { menuItem ->
- menuItem.isChecked = true
- mItemToOpenWhenDrawerCloses = menuItem.itemId
- mDrawerLayout!!.closeDrawers()
- true
- }
-
- if (SubSettingActivity::class.java.isAssignableFrom(javaClass)) {
- navigationView.setCheckedItem(R.id.sub_setting)
- } else if (SettingsActivity::class.java.isAssignableFrom(javaClass)) {
- navigationView.setCheckedItem(R.id.settings)
- }
- }
-}
diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainActivity.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainActivity.kt
index 23358065..eec16e03 100644
--- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainActivity.kt
+++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainActivity.kt
@@ -17,13 +17,16 @@ import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import com.tbruyelle.rxpermissions.RxPermissions
+import com.tencent.mmkv.MMKV
import com.v2ray.ang.AppConfig
import com.v2ray.ang.BuildConfig
import com.v2ray.ang.R
-import com.v2ray.ang.extension.defaultDPreference
+import com.v2ray.ang.dto.EConfigType
import com.v2ray.ang.extension.toast
import com.v2ray.ang.helper.SimpleItemTouchHelperCallback
+import com.v2ray.ang.service.V2RayServiceManager
import com.v2ray.ang.util.AngConfigManager
+import com.v2ray.ang.util.MmkvManager
import com.v2ray.ang.util.Utils
import com.v2ray.ang.util.V2rayConfigUtil
import com.v2ray.ang.viewmodel.MainViewModel
@@ -46,8 +49,10 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList
}
private val adapter by lazy { MainRecyclerAdapter(this) }
+ private val mainStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_MAIN, MMKV.MULTI_PROCESS_MODE) }
+ private val settingsStorage by lazy { MMKV.mmkvWithID(MmkvManager.ID_SETTING, MMKV.MULTI_PROCESS_MODE) }
private var mItemTouchHelper: ItemTouchHelper? = null
- private val mainViewModel: MainViewModel by lazy { ViewModelProviders.of(this).get(MainViewModel::class.java) }
+ val mainViewModel: MainViewModel by lazy { ViewModelProviders.of(this).get(MainViewModel::class.java) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
@@ -58,7 +63,7 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList
fab.setOnClickListener {
if (mainViewModel.isRunning.value == true) {
Utils.stopVService(this)
- } else if (defaultDPreference.getPrefString(AppConfig.PREF_MODE, "VPN") == "VPN") {
+ } else if (settingsStorage?.decodeString(AppConfig.PREF_MODE) ?: "VPN" == "VPN") {
val intent = VpnService.prepare(this)
if (intent == null) {
startV2Ray()
@@ -95,47 +100,65 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList
version.text = "v${BuildConfig.VERSION_NAME} (${Libv2ray.checkVersionX()})"
setupViewModelObserver()
+ migrateLegacy()
}
private fun setupViewModelObserver() {
mainViewModel.updateListAction.observe(this, {
val index = it ?: return@observe
if (index >= 0) {
- adapter.updateSelectedItem(index)
+ adapter.notifyItemChanged(index)
} else {
- adapter.updateConfigList()
+ adapter.notifyDataSetChanged()
}
})
mainViewModel.updateTestResultAction.observe(this, { tv_test_state.text = it })
mainViewModel.isRunning.observe(this, {
val isRunning = it ?: return@observe
- adapter.changeable = !isRunning
+ adapter.isRunning = isRunning
if (isRunning) {
fab.setImageResource(R.drawable.ic_v)
tv_test_state.text = getString(R.string.connection_connected)
+ layout_test.isFocusable = true
} else {
fab.setImageResource(R.drawable.ic_v_idle)
tv_test_state.text = getString(R.string.connection_not_connected)
+ layout_test.isFocusable = false
}
hideCircle()
})
mainViewModel.startListenBroadcast()
}
+ private fun migrateLegacy() {
+ GlobalScope.launch(Dispatchers.IO) {
+ val result = AngConfigManager.migrateLegacyConfig(this@MainActivity)
+ if (result != null) {
+ launch(Dispatchers.Main) {
+ if (result) {
+ toast(getString(R.string.migration_success))
+ mainViewModel.reloadServerList()
+ } else {
+ toast(getString(R.string.migration_fail))
+ }
+ }
+ }
+ }
+ }
+
fun startV2Ray() {
- if (AngConfigManager.configs.index < 0) {
+ if (mainStorage?.decodeString(MmkvManager.KEY_SELECTED_SERVER).isNullOrEmpty()) {
return
}
showCircle()
// toast(R.string.toast_services_start)
- if (!Utils.startVService(this, AngConfigManager.configs.index)) {
- hideCircle()
- }
+ V2RayServiceManager.startV2Ray(this)
+ hideCircle()
}
public override fun onResume() {
super.onResume()
- adapter.updateConfigList()
+ mainViewModel.reloadServerList()
}
public override fun onPause() {
@@ -171,9 +194,6 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList
return true
}
- private fun getOptionIntent() = Intent().putExtra("position", -1)
- .putExtra("isRunning", mainViewModel.isRunning.value == true)
-
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.import_qrcode -> {
importQRcode(REQUEST_SCAN)
@@ -184,18 +204,18 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList
true
}
R.id.import_manually_vmess -> {
- startActivity(getOptionIntent().setClass(this, ServerActivity::class.java))
- adapter.updateConfigList()
+ startActivity(Intent().putExtra("createConfigType", EConfigType.VMESS.value).
+ setClass(this, ServerActivity::class.java))
true
}
R.id.import_manually_ss -> {
- startActivity(getOptionIntent().setClass(this, Server3Activity::class.java))
- adapter.updateConfigList()
+ startActivity(Intent().putExtra("createConfigType", EConfigType.SHADOWSOCKS.value).
+ setClass(this, ServerActivity::class.java))
true
}
R.id.import_manually_socks -> {
- startActivity(getOptionIntent().setClass(this, Server4Activity::class.java))
- adapter.updateConfigList()
+ startActivity(Intent().putExtra("createConfigType", EConfigType.SOCKS.value).
+ setClass(this, ServerActivity::class.java))
true
}
R.id.import_config_custom_clipboard -> {
@@ -226,8 +246,8 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList
}
R.id.export_all -> {
- if (AngConfigManager.shareAll2Clipboard() == 0) {
- //remove toast, otherwise it will block previous warning message
+ if (AngConfigManager.shareNonCustomConfigsToClipboard(this, mainViewModel.serverList) == 0) {
+ toast(R.string.toast_success)
} else {
toast(R.string.toast_failure)
}
@@ -288,10 +308,13 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList
}
fun importBatchConfig(server: String?, subid: String = "") {
- val count = AngConfigManager.importBatchConfig(server, subid)
+ var count = AngConfigManager.importBatchConfig(server, subid)
+ if (count <= 0) {
+ count = AngConfigManager.importBatchConfig(Utils.decode(server!!), subid)
+ }
if (count > 0) {
toast(R.string.toast_success)
- adapter.updateConfigList()
+ mainViewModel.reloadServerList()
} else {
toast(R.string.toast_failure)
}
@@ -375,18 +398,16 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList
: Boolean {
try {
toast(R.string.title_sub_update)
- val subItem = AngConfigManager.configs.subItem
- for (k in 0 until subItem.count()) {
- if (TextUtils.isEmpty(subItem[k].id)
- || TextUtils.isEmpty(subItem[k].remarks)
- || TextUtils.isEmpty(subItem[k].url)
+ MmkvManager.decodeSubscriptions().forEach {
+ if (TextUtils.isEmpty(it.first)
+ || TextUtils.isEmpty(it.second.remarks)
+ || TextUtils.isEmpty(it.second.url)
) {
- continue
+ return@forEach
}
- val id = subItem[k].id
- val url = subItem[k].url
+ val url = it.second.url
if (!Utils.isValidUrl(url)) {
- continue
+ return@forEach
}
Log.d("Main", url)
GlobalScope.launch(Dispatchers.IO) {
@@ -397,7 +418,7 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList
""
}
launch(Dispatchers.Main) {
- importBatchConfig(Utils.decode(configText), id)
+ importBatchConfig(Utils.decode(configText), it.first)
}
}
}
@@ -434,9 +455,8 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList
.subscribe {
if (it) {
try {
- contentResolver.openInputStream(uri).use {
- val configText = it?.bufferedReader()?.readText()
- importCustomizeConfig(configText)
+ contentResolver.openInputStream(uri).use { input ->
+ importCustomizeConfig(input?.bufferedReader()?.readText())
}
} catch (e: Exception) {
e.printStackTrace()
@@ -450,19 +470,21 @@ class MainActivity : BaseActivity(), NavigationView.OnNavigationItemSelectedList
* import customize config
*/
fun importCustomizeConfig(server: String?) {
- if (server == null) {
- return
- }
- if (!V2rayConfigUtil.isValidConfig(server)) {
- toast(R.string.toast_config_file_invalid)
- return
- }
- val resId = AngConfigManager.importCustomizeConfig(server)
- if (resId > 0) {
- toast(resId)
- } else {
+ try {
+ if (server == null || TextUtils.isEmpty(server)) {
+ toast(R.string.toast_none_data)
+ return
+ }
+ if (!V2rayConfigUtil.isValidConfig(server)) {
+ toast(R.string.toast_config_file_invalid)
+ return
+ }
+ mainViewModel.appendCustomConfigServer(server)
toast(R.string.toast_success)
- adapter.updateConfigList()
+ adapter.notifyItemInserted(mainViewModel.serverList.lastIndex)
+ } catch (e: Exception) {
+ e.printStackTrace()
+ return
}
}
diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainRecyclerAdapter.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainRecyclerAdapter.kt
index ebd40b0d..26161149 100644
--- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainRecyclerAdapter.kt
+++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/MainRecyclerAdapter.kt
@@ -2,22 +2,25 @@ package com.v2ray.ang.ui
import android.content.Intent
import android.graphics.Color
+import android.support.v4.content.ContextCompat
import android.support.v7.app.AlertDialog
import android.support.v7.widget.RecyclerView
-import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
+import com.google.gson.Gson
+import com.tencent.mmkv.MMKV
import com.v2ray.ang.AppConfig
import com.v2ray.ang.R
-import com.v2ray.ang.dto.AngConfig
import com.v2ray.ang.dto.EConfigType
+import com.v2ray.ang.dto.SubscriptionItem
import com.v2ray.ang.extension.toast
import com.v2ray.ang.helper.ItemTouchHelperAdapter
import com.v2ray.ang.helper.ItemTouchHelperViewHolder
+import com.v2ray.ang.service.V2RayServiceManager
import com.v2ray.ang.util.AngConfigManager
+import com.v2ray.ang.util.MmkvManager
import com.v2ray.ang.util.Utils
-import com.v2ray.ang.util.V2rayConfigUtil
import kotlinx.android.synthetic.main.item_qrcode.view.*
import kotlinx.android.synthetic.main.item_recycler_main.view.*
import rx.Observable
@@ -32,83 +35,70 @@ class MainRecyclerAdapter(val activity: MainActivity) : RecyclerView.Adapter by lazy {
mActivity.resources.getStringArray(R.array.share_method)
}
+ var isRunning = false
- var changeable: Boolean = true
- set(value) {
- if (field == value)
- return
- field = value
- notifyDataSetChanged()
- }
-
- init {
- updateConfigList()
- }
-
- override fun getItemCount() = configs.vmess.count() + 1
+ override fun getItemCount() = mActivity.mainViewModel.serverList.size + 1
override fun onBindViewHolder(holder: BaseViewHolder, position: Int) {
if (holder is MainViewHolder) {
- val configType = EConfigType.fromInt(configs.vmess[position].configType)
- val remarks = configs.vmess[position].remarks
- val subid = configs.vmess[position].subid
- val address = configs.vmess[position].address
- val port = configs.vmess[position].port
- val test_result = configs.vmess[position].testResult
+ val guid = mActivity.mainViewModel.serverList.getOrNull(position) ?: return
+ val config = MmkvManager.decodeServerConfig(guid) ?: return
+ val outbound = config.getProxyOutbound() ?: return
+ val aff = MmkvManager.decodeServerAffiliationInfo(guid)
- holder.name.text = remarks
- holder.radio.isChecked = (position == configs.index)
+ holder.name.text = config.remarks
+ holder.radio.isChecked = guid == mainStorage?.decodeString(MmkvManager.KEY_SELECTED_SERVER)
holder.itemView.setBackgroundColor(Color.TRANSPARENT)
- holder.test_result.text = test_result
+ holder.test_result.text = aff?.getTestDelayString() ?: ""
+ if (aff?.testDelayMillis?:0L < 0L) {
+ holder.test_result.setTextColor(ContextCompat.getColor(mActivity, android.R.color.holo_red_dark))
+ } else {
+ holder.test_result.setTextColor(ContextCompat.getColor(mActivity, R.color.colorPing))
+ }
holder.subscription.text = ""
- if (!TextUtils.isEmpty(subid)) {
- for (sub in configs.subItem) {
- if (sub.id == subid) {
- holder.subscription.text = sub.remarks
- }
- }
+ val json = subStorage?.decodeString(config.subscriptionId)
+ if (!json.isNullOrBlank()) {
+ val sub = Gson().fromJson(json, SubscriptionItem::class.java)
+ holder.subscription.text = sub.remarks
}
var shareOptions = share_method.asList()
- if (configType == EConfigType.CUSTOM) {
+ if (config.configType == EConfigType.CUSTOM) {
holder.type.text = mActivity.getString(R.string.server_customize_config)
- val serverOutbound = V2rayConfigUtil.getCustomConfigServerOutbound(mActivity.applicationContext, configs.vmess[position].guid)
- if (serverOutbound == null) {
- holder.statistics.text = ""
- } else {
- holder.statistics.text = "${serverOutbound.getServerAddress()} : ${serverOutbound.getServerPort()}"
- }
shareOptions = shareOptions.takeLast(1)
+ } else if (config.configType == EConfigType.VLESS) {
+ holder.type.text = config.configType.name
} else {
- holder.type.text = configType?.name?.toLowerCase()
- holder.statistics.text = "$address : $port"
+ holder.type.text = config.configType.name.toLowerCase()
}
+ holder.statistics.text = "${outbound.getServerAddress()} : ${outbound.getServerPort()}"
holder.layout_share.setOnClickListener {
AlertDialog.Builder(mActivity).setItems(shareOptions.toTypedArray()) { _, i ->
try {
when (i) {
0 -> {
- if (configType == EConfigType.CUSTOM) {
- shareFullContent(position)
+ if (config.configType == EConfigType.CUSTOM) {
+ shareFullContent(guid)
} else {
- val iv = mActivity.layoutInflater.inflate(R.layout.item_qrcode, null)
- iv.iv_qcode.setImageBitmap(AngConfigManager.share2QRCode(position))
+ val iv = LayoutInflater.from(mActivity).inflate(R.layout.item_qrcode, null)
+ iv.iv_qcode.setImageBitmap(AngConfigManager.share2QRCode(guid))
AlertDialog.Builder(mActivity).setView(iv).show()
}
}
1 -> {
- if (AngConfigManager.share2Clipboard(position) == 0) {
+ if (AngConfigManager.share2Clipboard(mActivity, guid) == 0) {
mActivity.toast(R.string.toast_success)
} else {
mActivity.toast(R.string.toast_failure)
}
}
- 2 -> shareFullContent(position)
+ 2 -> shareFullContent(guid)
else -> mActivity.toast("else")
}
} catch (e: Exception) {
@@ -118,43 +108,39 @@ class MainRecyclerAdapter(val activity: MainActivity) : RecyclerView.Adapter
- return MainViewHolder(LayoutInflater.from(parent.context)
+ MainViewHolder(LayoutInflater.from(parent.context)
.inflate(R.layout.item_recycler_main, parent, false))
else ->
- return FooterViewHolder(LayoutInflater.from(parent.context)
+ FooterViewHolder(LayoutInflater.from(parent.context)
.inflate(R.layout.item_recycler_footer, parent, false))
}
}
- fun updateConfigList() {
- configs = AngConfigManager.configs
- notifyDataSetChanged()
- }
-
-// fun updateSelectedItem() {
-// updateSelectedItem(configs.index)
-// }
-
- fun updateSelectedItem(pos: Int) {
- //notifyItemChanged(pos)
- notifyItemRangeChanged(pos, itemCount - pos)
- }
-
override fun getItemViewType(position: Int): Int {
- if (position == configs.vmess.count()) {
- return VIEW_TYPE_FOOTER
+ return if (position == mActivity.mainViewModel.serverList.size) {
+ VIEW_TYPE_FOOTER
} else {
- return VIEW_TYPE_ITEM
+ VIEW_TYPE_ITEM
}
}
open class BaseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
class MainViewHolder(itemView: View) : BaseViewHolder(itemView), ItemTouchHelperViewHolder {
- val subscription = itemView.tv_subscription
+ val subscription = itemView.tv_subscription!!
val radio = itemView.btn_radio!!
val name = itemView.tv_name!!
val test_result = itemView.tv_test_result!!
@@ -246,28 +218,26 @@ class MainRecyclerAdapter(val activity: MainActivity) : RecyclerView.Adapter? = null
+ private val defaultSharedPreferences by lazy { PreferenceManager.getDefaultSharedPreferences(this) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
@@ -52,7 +49,7 @@ class PerAppProxyActivity : BaseActivity() {
val dividerItemDecoration = DividerItemDecoration(this, LinearLayoutManager.VERTICAL)
recycler_view.addItemDecoration(dividerItemDecoration)
- val blacklist = defaultDPreference.getPrefStringSet(PREF_PER_APP_PROXY_SET, null)
+ val blacklist = defaultSharedPreferences.getStringSet(AppConfig.PREF_PER_APP_PROXY_SET, null)
AppManagerUtil.rxLoadNetworkAppList(this)
.subscribeOn(Schedulers.io())
@@ -141,15 +138,15 @@ class PerAppProxyActivity : BaseActivity() {
}
})
- switch_per_app_proxy.setOnCheckedChangeListener { buttonView, isChecked ->
- defaultDPreference.setPrefBoolean(SettingsActivity.PREF_PER_APP_PROXY, isChecked)
+ switch_per_app_proxy.setOnCheckedChangeListener { _, isChecked ->
+ defaultSharedPreferences.edit().putBoolean(AppConfig.PREF_PER_APP_PROXY, isChecked).apply()
}
- switch_per_app_proxy.isChecked = defaultDPreference.getPrefBoolean(SettingsActivity.PREF_PER_APP_PROXY, false)
+ switch_per_app_proxy.isChecked = defaultSharedPreferences.getBoolean(AppConfig.PREF_PER_APP_PROXY, false)
- switch_bypass_apps.setOnCheckedChangeListener { buttonView, isChecked ->
- defaultDPreference.setPrefBoolean(PREF_BYPASS_APPS, isChecked)
+ switch_bypass_apps.setOnCheckedChangeListener { _, isChecked ->
+ defaultSharedPreferences.edit().putBoolean(AppConfig.PREF_BYPASS_APPS, isChecked).apply()
}
- switch_bypass_apps.isChecked = defaultDPreference.getPrefBoolean(PREF_BYPASS_APPS, false)
+ switch_bypass_apps.isChecked = defaultSharedPreferences.getBoolean(AppConfig.PREF_BYPASS_APPS, false)
et_search.setOnEditorActionListener { v, actionId, event ->
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
@@ -183,7 +180,7 @@ class PerAppProxyActivity : BaseActivity() {
override fun onPause() {
super.onPause()
adapter?.let {
- defaultDPreference.setPrefStringSet(PREF_PER_APP_PROXY_SET, it.blacklist)
+ defaultSharedPreferences.edit().putStringSet(AppConfig.PREF_PER_APP_PROXY_SET, it.blacklist).apply()
}
}
diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/RoutingSettingsFragment.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/RoutingSettingsFragment.kt
index 97917148..993c2d32 100644
--- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/RoutingSettingsFragment.kt
+++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/RoutingSettingsFragment.kt
@@ -5,9 +5,9 @@ import android.app.Activity.RESULT_OK
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
+import android.support.v7.preference.PreferenceManager
import android.view.*
import com.v2ray.ang.R
-import com.v2ray.ang.extension.defaultDPreference
import com.v2ray.ang.util.Utils
import kotlinx.android.synthetic.main.fragment_routing_settings.*
import android.view.MenuInflater
@@ -26,6 +26,8 @@ class RoutingSettingsFragment : Fragment() {
private const val REQUEST_SCAN_APPEND = 12
}
+ val defaultSharedPreferences by lazy { PreferenceManager.getDefaultSharedPreferences(context) }
+
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
@@ -40,10 +42,10 @@ class RoutingSettingsFragment : Fragment() {
return fragment
}
- override fun onActivityCreated(savedInstanceState: Bundle?) {
- super.onActivityCreated(savedInstanceState)
+ override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
+ super.onViewCreated(view, savedInstanceState)
- val content = activity?.defaultDPreference?.getPrefString(arguments!!.getString(routing_arg), "")
+ val content = defaultSharedPreferences.getString(arguments!!.getString(routing_arg), "")
et_routing_content.text = Utils.getEditable(content!!)
setHasOptionsMenu(true)
@@ -57,7 +59,7 @@ class RoutingSettingsFragment : Fragment() {
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.save_routing -> {
val content = et_routing_content.text.toString()
- activity?.defaultDPreference?.setPrefString(arguments!!.getString(routing_arg), content)
+ defaultSharedPreferences.edit().putString(arguments!!.getString(routing_arg), content).apply()
activity?.toast(R.string.toast_success)
true
}
diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ScannerActivity.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ScannerActivity.kt
index 6f1dafd1..5e973cb8 100644
--- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ScannerActivity.kt
+++ b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/ScannerActivity.kt
@@ -23,8 +23,8 @@ class ScannerActivity : BaseActivity(), ZXingScannerView.ResultHandler {
private var mScannerView: ZXingScannerView? = null
- public override fun onCreate(state: Bundle?) {
- super.onCreate(state)
+ public override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
mScannerView = ZXingScannerView(this) // Programmatically initialize the scanner view
mScannerView?.setAutoFocus(true)
diff --git a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/Server2Activity.kt b/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/Server2Activity.kt
deleted file mode 100644
index 23d995a1..00000000
--- a/V2rayNG/app/src/main/kotlin/com/v2ray/ang/ui/Server2Activity.kt
+++ /dev/null
@@ -1,152 +0,0 @@
-package com.v2ray.ang.ui
-
-import android.os.Bundle
-import android.support.v7.app.AlertDialog
-import android.text.Editable
-import android.text.TextUtils
-import android.view.Menu
-import android.view.MenuItem
-import com.google.gson.Gson
-import com.v2ray.ang.AppConfig
-import com.v2ray.ang.R
-import com.v2ray.ang.extension.defaultDPreference
-import com.v2ray.ang.dto.AngConfig
-import com.v2ray.ang.extension.toast
-import com.v2ray.ang.util.AngConfigManager
-import com.v2ray.ang.util.Utils
-import kotlinx.android.synthetic.main.activity_server2.*
-import java.lang.Exception
-
-class Server2Activity : BaseActivity() {
- companion object {
- private const val REQUEST_SCAN = 1
- }
-
- var del_config: MenuItem? = null
- var save_config: MenuItem? = null
-
- private lateinit var configs: AngConfig
- private var edit_index: Int = -1 //当前编辑的服务器
- private var edit_guid: String = ""
- private var isRunning: Boolean = false
-
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_server2)
-
- configs = AngConfigManager.configs
- edit_index = intent.getIntExtra("position", -1)
- isRunning = intent.getBooleanExtra("isRunning", false)
- title = getString(R.string.title_server)
-
- if (edit_index >= 0) {
- edit_guid = configs.vmess[edit_index].guid
- bindingServer(configs.vmess[edit_index])
- } else {
- clearServer()
- }
- supportActionBar?.setDisplayHomeAsUpEnabled(true)
- }
-
- /**
- * bingding seleced server config
- */
- fun bindingServer(vmess: AngConfig.VmessBean): Boolean {
- et_remarks.text = Utils.getEditable(vmess.remarks)
- tv_content.text = Editable.Factory.getInstance().newEditable(defaultDPreference.getPrefString(AppConfig.ANG_CONFIG + edit_guid, ""))
- return true
- }
-
- /**
- * clear or init server config
- */
- fun clearServer(): Boolean {
- et_remarks.text = null
- return true
- }
-
- /**
- * save server config
- */
- fun saveServer(): Boolean {
- val vmess = configs.vmess[edit_index]
-
- vmess.remarks = et_remarks.text.toString()
-
- if (TextUtils.isEmpty(vmess.remarks)) {
- toast(R.string.server_lab_remarks)
- return false
- }
-
- try {
- Gson().fromJson