is there any way how to take advantage of ContentProvider to check, whether my Android phone is connected to the internet?
Thanks
// check internet connectivity
public static boolean isNetworkAvailable(Context context) {
boolean networkStatus;
try {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
networkStatus = (activeNetworkInfo != null && activeNetworkInfo.isConnected()) ? true : false;
} catch (Exception e) {
e.printStackTrace();
DinotaLogger.log(e, Level.SEVERE);
networkStatus = false;
}
return networkStatus;
}
Please make sure to put in manifest file. If you are using an emulator to check this, press F8 to disable network access. This works fine with android 2.3.3 emulator.
I think you want ConnectivityManager. There's an example here.
That explains how to register for notifications. To check directly, you can get a ConnectivityManager instance:
ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = mgr.getActiveNetworkInfo();
boolean is_connected = info.isConnected();
boolean is_available = info.isAvailable();
this code should help you to query if the data network is available or not:
public static boolean isDataNetworkAvailable(Context context){
try{
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
catch (Exception e) { return false; }
}
It will tell you in boolean that your android is connected to internet.
I used that:
public boolean isNetworkAvailable() {
try{
Context context = getApplicationContext();
ConnectivityManager connectivity = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
}else{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
}catch (Exception e) {
System.out.println("error");
}
return false;
}
Also put:
<uses-permission> android:name="android.permission.ACCESS_NETWORK_STATE" />
this line to your android manifest.
I Used this in my application.
来源:https://stackoverflow.com/questions/9000169/android-contentprovider-check-network-access