一,Android7.0以后Broadcast Receiver发生了变化,在静态注册时,接收不到CONNECTIVITY_ACTION 广播
因此,我使用的是动态注册(这样就需要每个Acticity都进行注册和注销)
现在我创建一个library库进行封装:
1,AndroidManifest.xml添加网络监听权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/><uses-permission android:name="android.permission.INTERNET"/>
2,创建一个广播接收器:
MyNetworkReceiver
public class MyNetworkReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {boolean isconnect = false; //判断是否连接网络//获取网络连接服务ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(context.CONNECTIVITY_SERVICE);//判断wifi是否连接NetworkInfo.State state = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();if (state == NetworkInfo.State.CONNECTED){isconnect = true;Log.i("TAG","wifi连接");}//判断GPRS是否连接NetworkInfo.State gstate = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();if (gstate == NetworkInfo.State.CONNECTED){isconnect = true;Log.i("TAG","GPRS连接");}//没网络连接if (!isconnect){Toast.makeText(context , "没网络连接",Toast.LENGTH_LONG).show();}}
}
如图wifi和GPRS分别打印:
3,动态注册:
public class NetworkActivity extends AppCompatActivity {MyNetworkReceiver myNetworkReceiver;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_network);//动态注册广播myNetworkReceiver = new MyNetworkReceiver();IntentFilter intentFilter = new IntentFilter();intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");registerReceiver(myNetworkReceiver , intentFilter);}@Overrideprotected void onDestroy() {super.onDestroy();//注销广播unregisterReceiver(myNetworkReceiver);}
}