ConnectivityManager
NetworkInfo
授予 app 權限
AndroidManifest.xml:
... ... <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> ... ...
android { compileSdk 33 ... ... buildFeatures { viewBinding true } ... ... }
<?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:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/txtHello" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.kt
... ... class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) val view = binding.root setContentView(view) } override fun onResume() { super.onResume() val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION) registerReceiver(connectivityReceiver, filter) } override fun onPause() { super.onPause() unregisterReceiver(connectivityReceiver) } fun updateTextView(message: String) { binding.txtHello.text = message } ... ... private val connectivityReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { val connectivityManager = context?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val networkInfo = connectivityManager.activeNetworkInfo if (networkInfo != null && networkInfo.isConnected) { (context as MainActivity).updateTextView("已連線") } else { (context as MainActivity).updateTextView("已斷線") } } } } ... ...
相關筆記 ----
沒有留言:
張貼留言