android获取及监听手机网络状态
程序员文章站
2022-06-09 19:38:14
目录一、获取当前手机联网方式是wifi还是手机4g数据二、监听手机网络变化总结一、获取当前手机联网方式是wifi还是手机4g数据private boolean getnetworktype(){...
一、获取当前手机联网方式是wifi还是手机4g数据
private boolean getnetworktype(){ connectivitymanager mconnectivity = (connectivitymanager)getsystemservice(context.connectivity_service); //检查网络链接 networkinfo info = mconnectivity.getactivenetworkinfo(); int nettype = mconnectivity.getactivenetworkinfo().gettype(); if (nettype == connectivitymanager.type_wifi) { //wifi changyoulog.i(tag,"当前是wifi连接 isconnected = "+info.isconnected()); return info.isconnected(); } else if (nettype == connectivitymanager.type_mobile) { //mobile changyoulog.i(tag,"当前是手机网络连接 isconnected = "+info.isconnected()); return info.isconnected(); } else { changyoulog.i(tag,"当前没有网络连接 isconnected = "+info.isconnected()); return false; } }
二、监听手机网络变化
private class mybroadcastreceiver extends broadcastreceiver{ @override public void onreceive(context context, intent intent) { if (intent.getaction().equals(connectivitymanager.connectivity_action)) {//监听网络连接 //获取联网状态的networkinfo对象 networkinfo info = intent.getparcelableextra(connectivitymanager.extra_network_info); if (info != null) { //如果当前的网络连接成功并且网络连接可用 if (networkinfo.state.connected == info.getstate() && info.isavailable()) { if (info.gettype() == connectivitymanager.type_wifi){ changyoulog.i(tag,"连接上wifi"); }else if (info.gettype() == connectivitymanager.type_mobile){ changyoulog.i(tag,"连接上移动网络数据"); cyoulbymicroclient.getinstance().gameevent("network_4g_reminder"); } } else { changyoulog.i(tag,"网络断开"); } } } } }
注:需要添加网络状态权限
<uses-permission android:name="android.permission.access_network_state" /> <uses-permission android:name="android.permission.access_wifi_state" />
总结
到此这篇关于android获取及监听手机网络状态的文章就介绍到这了,更多相关android网络状态内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!