[关闭]
@cxm-2016 2016-09-22T16:15:50.000000Z 字数 618 阅读 1836

Android:如何监听网络状态

android no


1,创建一个广播接收者

  1. class NetStateReceiver : BroadcastReceiver() {
  2. override fun onReceive(context: Context, intent: Intent?) {
  3. val net = NetUtils(context)
  4. Urls.networkState = net.NETWORK_TYPE
  5. Log.e("NetState", "${Urls.networkState.name}")
  6. }
  7. }

2,在清单文件中注册广播接收者

  1. <receiver android:name=".component.broadcast.NetStateReceiver">
  2. <intent-filter>
  3. <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
  4. </intent-filter>
  5. </receiver>

3,在Activity或者Application中启动广播接收者

  1. override fun onCreate() {
  2. ...
  3. val receiver = NetStateBroadCast()
  4. val filter = IntentFilter()
  5. filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
  6. registerReceiver(receiver, filter)
  7. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注