請改參考這篇 -- 【Kotlin】socket ping 判斷是否連上網際網路
以下備存,做為學習歷程的記錄
在爬文的過程中, 也有看到認為這不可靠的觀點......所以,再繼續尋找更好的做法吧......
===== 2023.03.23 =====
拿手邊的幾支 Android 裝置實測,在同樣的 Wi-Fi 環境中
ASUS Zenfone3(Android8.0) -- 正常
華為 T3 平板(Android7.0) -- 反應網路不通,但 app 內的 AdMob 廣告播放正常,表示 app 在 T3 執行時誤判。
SugarY12S(AndroidGo8.1.0) -- 正常
ASUS Zenfone5(Android9) -- 正常
小米 POCO X4 PRO(Android12) -- 正常
app 層級的 build.gradle
- ...
- ...
- android {
- ...
- ...
- buildFeatures {
- viewBinding true
- }
- buildTypes {
- ...
- ...
- }
- }
- dependencies {
- implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.4")
- }
- ...
- ...
- <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:onClick="isConnected"
- android:text="Hello World!"
- android:textSize="20sp"
- app:layout_constraintBottom_toBottomOf="parent"
- app:layout_constraintEnd_toEndOf="parent"
- app:layout_constraintStart_toStartOf="parent"
- app:layout_constraintTop_toTopOf="parent" />
- </androidx.constraintlayout.widget.ConstraintLayout>
- import android.content.ContentValues.TAG
- import androidx.appcompat.app.AppCompatActivity
- import android.os.Bundle
- import android.util.Log
- import android.view.View
- import android.widget.Toast
- import com.example.pingconn.databinding.ActivityMainBinding
- import kotlinx.coroutines.Dispatchers
- import kotlinx.coroutines.GlobalScope
- import kotlinx.coroutines.launch
- import kotlinx.coroutines.withContext
- import java.io.IOException
- import java.net.InetAddress
- class MainActivity : AppCompatActivity() {
- val TAG = "MainActivity"
- private lateinit var binding: ActivityMainBinding
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- binding = ActivityMainBinding.inflate(layoutInflater)
- val view = binding.root
- setContentView(view)
- }
- fun isConnected(vv: View)
- {
- // Toast.makeText(this, "test", Toast.LENGTH_SHORT).show()
- GlobalScope.launch {
- val address = "8.8.8.8"
- val isReachable = myPing(address)
- withContext(Dispatchers.Main) {
- updateUI(isReachable)
- }
- }
- }
- private fun updateUI(isReachable: Boolean) {
- if(isReachable)
- binding.lblHello.text = "internet connected"
- else
- binding.lblHello.text = "no internet"
- }
- suspend fun myPing(address: String): Boolean = withContext(Dispatchers.IO) {
- try {
- val inetAddress = InetAddress.getByName(address)
- inetAddress.isReachable(500) // 單位:毫秒,
- } catch (e: Exception) {
- false
- }
- }
- }
沒有留言:
張貼留言