Android 网络监听、 网络位置和运营商获取

判断有无网络连接

object NetworkUtils {
	fun isNetworkAvailable(): Boolean{
		val connMgr = BaseApplication.application.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
			//高版本使用NetworkCapabilities来判断有无网络
			val networkCapabilities = connMgr.getNetworkCapabilities(connMgr.activeNetwork)
			return networkCapabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED) ?: false
		} else {
			//低版本直接使用networkInfo
			val networkInfo = connMgr.activeNetworkInfo
			return networkInfo?.isConnected ?: false
		}
	}
}

网络变换实时监听

object NetworkUtils {
	fun setNetworkChangeListener(context: Context?){
		val connMgr = BaseApplication.application.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			//高版本使用ConnectivityManager.NetworkCallback来监听网络状态变更
			connMgr.requestNetwork(NetworkRequest.Builder().build(), object : ConnectivityManager.NetworkCallback(){
				override fun onAvailable(network: Network) {
					super.onAvailable(network)
					Toast.makeText(BaseApplication.application, "网络已连接啊", Toast.LENGTH_SHORT).show()
				}
	
				override fun onLost(network: Network) {
					super.onLost(network)
					Toast.makeText(BaseApplication.application, "网络已断开啊", Toast.LENGTH_SHORT).show()
				}
			})
		}else{
			//低版本需要使用广播来接收
			val intentFilter = IntentFilter()
			intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
			context?.registerReceiver(NetworkReceiver(), intentFilter)
		}
	}
}

/**
 * 网络状态监听广播
 */
class NetworkReceiver: BroadcastReceiver(){
    override fun onReceive(context: Context?, intent: Intent?) {
        if (intent?.action.equals(ConnectivityManager.CONNECTIVITY_ACTION)){
            if (NetworkUtils.isNetworkAvailable()){
                Toast.makeText(BaseApplication.application, "网络已连接啊", Toast.LENGTH_SHORT).show()
            }else{
                Toast.makeText(BaseApplication.application, "网络已断开啊", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

网络位置和运营商信息获取

有个需求是获取网络位置和运营商,由于版本可能运行在手机、pad、tv和盒子上,所以这边采用的方案是使用webServices来获取,如果有更好的麻烦告知一下,谢谢

获取网络信息的WebService有很多可以参考这里,下面示例是对比了几个最终使用太平洋电脑网的。

如果有其他信息需要获取可以看这里, 或者直接在网上搜素其他WebServices,比如天气、号码归属地等

public interface NetworkInfoFromTPY {
    @GET("ip.jsp")
    Call<ResponseBody> getAddressFromTPY();
}

fun getNetworkInfoFromTPY(view: View){
	//这边使用太平洋WebServices来获取网络位置以及运营商
	val retrofit = Retrofit.Builder()
		.baseUrl("http://whois.pconline.com.cn/")
		.build()
	val networkInfo = retrofit.create(NetworkInfoFromTPY::class.java)
	val infoFromWeb = networkInfo.addressFromTPY
	infoFromWeb.enqueue(object : Callback<ResponseBody> {
		override fun onResponse(call: Call<ResponseBody>, response: Response<ResponseBody>) {
			Log.i(TAG, "infoFromWeb body is ${response.body()?.string()?.trim()}")
		}

		override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
			Log.i(TAG, "infoFromWeb Throwable is ${t.message}")
		}

	})
}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页