Android Network Connectivity ServicesAndroid network connectivity services allow us to check the network connectivity information of the device. It is very important to check the internet connection of the device while performing the task which is based on internet service such as fetching data from the server (internet) or writing data to the server. Using Android Network Connectivity Services we can also determine the types of a network of android device. It may be of types TYPE_WIFI (wifi), TYPE_MOBILE (mobile), TYPE_BLUETOOTH (Bluetooth), etc. Android Network Connectivity Service ExampleLet's create a simple example to check the network connectivity of the device as well as its type. To access the network connectivity of a device, we need to provide the network access permission in AndroidMenifest.xml file. In the activity_main.xml file of layout add the following code. For accessing the network state of a device, there is no requirement of the layout file. Here, we are using the activity_main.xml file only for storing the state of network type. activity_main.xmlCreate a java class named as NetworkState.java. This class contains a getConnectivityStatus() method which returns the constant integer value on the basis of current network connection. The code context.getSystemService(Context.CONNECTIVITY_SERVICE) is used to return the instance of the ConnectivityManager class which access the network properties. NetworkState.javaCreate a receiver class named as NetworkReceiver.java and extends the BroadcastReciever class. This class handles the changes occur in the network state of a device. The onReceive() method of BroadcastReciever class called when the network state of device changes. NetworkReceiver.javaIn the MainActivity.java class, we are displaying the network state of a device in TextView by clicking the Button. MainActivity.javaIn the AndroidMenifest.xml file, add the network access permission and receiver class that handles the changes occur in BroadcastReceiver class. AndroidMenifest.xmlOutput Next TopicFirebase Authentication - Google Login |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India