Luckily, there's an easy way to check for data connections prior to making calls so you can either proceed or handle gracefully. The sample class below provides everything you need. Just insert into your project and call when necessary...
public class Networking { /* *@return boolean return true if the application can access the internet */ public static boolean isNetworkAvailable(Context context) { ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity != null) { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) { for (int i = 0; i < info.length; i++) { if (info[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } } } return false; } }
Thanks for valuable information.
ReplyDeletethis is great.This was really helpful in my project.
ReplyDeleteHowever I wish to know if there is anyway to modify this code so that only selected applications can access the internet through 3G while other applications that are not selected will not be able to use 3G data connection.
This is the last part of my project and I have been looking for a solution and I have not found any. only this was the closest thing to a solution.
I hope to get your opinion on my problem.
This comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteRemember to add:
ReplyDeleteandroid.permission.ACCESS_NETWORK_STATE
to AndroidManifest.xml
Thanks for the nice tutorial man... Even this http://www.compiletimeerror.com/2013/06/check-internet-connection-in-android.html might help, have a look...
ReplyDelete