我在我的Android应用程序中使用了互联网。我从服务器获取数据,因为用户尝试在服务器上请求,我必须检查互联网连接。我能做些什么呢?
答案 0 :(得分:0)
这是我用来检查我的应用程序是否已连接到Internet的功能。
private void CheckEnabledInternet() {
boolean isConnected = false;
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo[] networkInfos = connectivityManager.getAllNetworkInfo();
for(NetworkInfo networkInfo : networkInfos) {
if(networkInfo.getState()== NetworkInfo.State.CONNECTED) {
isConnected = true;
break;
}
}
if(!isConnected) {
AlertDialog.Builder networkDialog = new AlertDialog.Builder(this);
networkDialog.setTitle("Not Connected");
networkDialog.setMessage("Please connect to internet to proceed");
networkDialog.setCancelable(false);
networkDialog.setPositiveButton("Okay!",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
CheckEnabledInternet();
}
});
networkDialog.create().show();
}
}