-
Notifications
You must be signed in to change notification settings - Fork 0
/
Android_CellularConnection.kt
147 lines (124 loc) · 5.59 KB
/
Android_CellularConnection.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import android.annotation.TargetApi
import android.content.Context
import android.content.Context.CONNECTIVITY_SERVICE
import android.net.ConnectivityManager
import android.net.ConnectivityManager.NetworkCallback
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
import android.os.Build
import android.util.Log
import okhttp3.*
class CellularTest {
// required permission: INTERNET, ACCESS_WIFI_STATE, ACCESS_NETWORK_STATE, CHANGE_NETWORK_STATE
// external library: OkHttp : com.squareup.okhttp3:okhttp
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun callAPIonCellularNetwork(context: Context, url: String) {
// 1. check if cellular network is enabled
// 2. force network connection via cellular interface
val connectivityManager =
context.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
val request = NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build()
// If your app supports Android 21+, you need to implement handling timeout.
// Android 21++ support requestNetwork (NetworkRequest request,
// ConnectivityManager.NetworkCallback networkCallback)
// Android 26++ support requestNetwork(NetworkRequest request,
// ConnectivityManager.NetworkCallback networkCallback,
// int timeoutMs)
// https://developer.android.com/reference/android/net/ConnectivityManager#requestNetwork(android.net.NetworkRequest,%20android.net.ConnectivityManager.NetworkCallback)
connectivityManager.requestNetwork(request, object : NetworkCallback() {
override fun onAvailable(network: Network) {
//using OkHTTP library to make the connection
val httpBuilder =
OkHttpClient.Builder().socketFactory(network.socketFactory)
// enable dns based on cellular network
val dns = NetworkDns.instance
dns.setNetwork(network)
httpBuilder.dns(dns)
val okHttpClient = httpBuilder.build()
val mRequestBuilder = Request.Builder()
.url(url)
try {
val response: Response = okHttpClient.newCall(mRequestBuilder.build()).execute()
Log.i(
"TestAPI", " callAPIonCellularNetwork RESULT:${response.body?.string()}"
)
} catch (ex: Exception) {
ex.printStackTrace()
Log.e("TestAPI", ex.message!!)
}
}
override fun onUnavailable() {
// cellular network is not available, callback
Log.e("TestAPI","cellular network is not available")
}
}
, 5000 // CONNECT_NETWORK_TIMEOUT
)
}
}
--------------------------
NetworkDns.kt
--------------------------
import android.net.Network
import android.os.Build
import android.os.Build.VERSION_CODES
import okhttp3.Dns
import java.net.InetAddress
import java.net.UnknownHostException
class NetworkDns private constructor() : Dns {
private var mNetwork: Network? = null
fun setNetwork(network: Network?) {
mNetwork = network
}
@Throws(UnknownHostException::class)
override fun lookup(hostname: String): List<InetAddress> {
return if (mNetwork != null && Build.VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
listOf(*mNetwork!!.getAllByName(hostname))
} else Dns.SYSTEM.lookup(hostname)
}
companion object {
private var sInstance: NetworkDns? = null
val instance: NetworkDns
get() {
if (sInstance == null) {
sInstance = NetworkDns()
}
return sInstance!!
}
}
}
--------------------------
HandleRedirectInterceptor.kt (need to implement in case handling redirect urls)
--------------------------
import android.content.Context
import android.os.Build
import android.util.Log
import okhttp3.*
import okhttp3.ResponseBody.Companion.toResponseBody
class HandleRedirectInterceptor(ctx: Context, requestUrl: String, redirect_uri: String) : Interceptor {
private var redirectUri: String = redirect_uri
private var url: String = requestUrl
override fun intercept(chain: Interceptor.Chain): Response {
val request: Request = chain.request()
val response: Response = response = chain.proceed(request)
// check and return success response if location match with defined redirect-uri
if (response.code in 300.. 399){
if ((response.headers["location"] != null && response.headers["location"]!!.startsWith(redirectUri))
|| (response.headers["Location"] != null && response.headers["Location"]!!.startsWith(redirectUri)))
{
val builder: Response.Builder = Response.Builder().request(request).protocol(Protocol.HTTP_1_1)
val contentType: MediaType? = response.body!!.contentType()
val locationRes = response.headers["location"] ?: response.headers["Location"] ?: ""
val body = locationRes.toResponseBody(contentType)
builder.code(200).message("success").body(body)
// close the response body
response.body?.close()
return builder.build()
}
}
return response
}
}