參考資料 ----
OkHttp 是輕量型的 3rd party library,這篇筆記只是記錄透過 OkHttp 偵測 Android 裝置是否有連上網際網路。
上網比較了幾個網站,選定目標網站是網頁內容(html 字數,包含 CSS, javascript...) 最少的 example.com。
app 層級的 build.gradle
- ...
- ...
- android {
- ...
- ...
- buildFeatures {
- viewBinding true
- }
- buildTypes {
- ...
- ...
- }
- }
- ...
- ...
- dependencies {
- ...
- ...
- implementation 'com.squareup.okhttp3:okhttp:4.7.2'
- }
- <uses-permission android:name="android.permission.INTERNET"/>
- <application
- ...
- ...
- <?xml version="1.0" encoding="utf-8"?>
- <androidx.constraintlayout.widget.ConstraintLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:app="http://schemas.android.com/apk/res-auto"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- tools:context=".MainActivity">
- <TextView
- android:id="@+id/lblHello"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Hello World!"
- app:layout_constraintBottom_toBottomOf="parent"
- app:layout_constraintEnd_toEndOf="parent"
- app:layout_constraintStart_toStartOf="parent"
- app:layout_constraintTop_toTopOf="parent" />
- <Button
- android:id="@+id/btnCheck"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="check internet"
- app:layout_constraintBottom_toBottomOf="parent"
- app:layout_constraintEnd_toEndOf="parent"
- app:layout_constraintHorizontal_bias="0.064"
- app:layout_constraintStart_toStartOf="parent"
- app:layout_constraintTop_toTopOf="parent"
- app:layout_constraintVertical_bias="0.023"
- android:onClick="onBtnClicked"/>
- </androidx.constraintlayout.widget.ConstraintLayout>
- ...
- ...
- import android.os.Bundle
- import android.util.Log
- import android.view.View
- import androidx.appcompat.app.AppCompatActivity
- import com.example.okhp.databinding.ActivityMainBinding
- import okhttp3.*
- import okio.IOException
- class MainActivity : AppCompatActivity() {
- val TAG = "MyTag"
- private lateinit var binding: ActivityMainBinding
- private lateinit var client: OkHttpClient
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- binding = ActivityMainBinding.inflate(layoutInflater)
- val view = binding.root
- setContentView(view)
- }
- fun onBtnClicked(vv: View) {
- val client = OkHttpClient()
- val request = Request.Builder()
- .url("https://example.com")
- .build()
- client.newCall(request).enqueue(object : Callback {
- override fun onResponse(call: Call, response: Response) {
- // Log.d(TAG, "response: ${response.body?.string()}")
- runOnUiThread {
- binding.lblHello.text = "connected"
- }
- }
- override fun onFailure(call: Call, e: IOException) {
- // Log.d(TAG, e.toString())
- runOnUiThread {
- binding.lblHello.text = "no internet"
- }
- }
- })
- }
- }
跟 Volley 稍微比較了一下,OkHttp3 速度確實快了一些。
沒有留言:
張貼留言