Reputation: 15
Earlier I used to verify Internet connection and display data accordingly. If it is connected to Internet I used to load data from server and if there is no Internet connection, I used to load offline data. But from Android Studio 2.2.1, however this seems not to be working. The code I used was:
import android.app.Service;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectionDetector {
Context context;
public ConnectionDetector(Context context) {
this.context = context;
}
public boolean isConnected(){
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Service.CONNECTIVITY_SERVICE);
if(connectivity!=null){
NetworkInfo info = connectivity.getActiveNetworkInfo();
if(info!=null){
if(info.getState()== NetworkInfo.State.CONNECTED){
return true;
}
}
}
return false;
}
I would create new object of this class :
cd = new ConnectionDetector(this);
and then use:
if(cd.isConnected()){
-----------
---------
}else {
------
---
}
But this is not working in 2.2.1 What changes are needed to make it work in 2.2.1 ? I am not a programming expert.
Upvotes: 1
Views: 732
Reputation:
Please Use this for device is connected OR Not.
public class ConnectivityDetector {
public static boolean isConnectingToInternet(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;
}}
You Can check it like this :
if (ConnectivityDetector.isConnectingToInternet(ChangePasswordActivity.this)) {
//Your Code when connected.
} else {
Toast.makeText(MainActivity.this, "Please check your Internet connection.", Toast.LENGTH_SHORT).show();
}
Upvotes: 3