Hello Friends,
Add some important permissions in AndroidManifiest.xml file.
STEP : 2
Create function which checks whether internet connection is available in device or not?
- Finally you can call this method before doing network related task like calling API or downloading/uploading something to server.
- If this method return true then do network operation else show network error to user.
- In this post i am going to show how we can check "Network Reachability" in Android using simple code.
- We can use this code in our app while calling API or other network related stuffs.STEP : 1
Add some important permissions in AndroidManifiest.xml file.
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
STEP : 2
Create function which checks whether internet connection is available in device or not?
public static boolean hasConnection(Context context) { ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); if (activeNetwork != null) { // connected to the internet if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) { // connected to wifi return true; } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) { // connected to the mobile provider's data plan return true; } } else return false; return false; }
- Finally you can call this method before doing network related task like calling API or downloading/uploading something to server.
- If this method return true then do network operation else show network error to user.
Happy Coding ;)
Comments
Post a Comment
Thanks, I'll respond you soon!