在我的Android应用程序中,我正在检查我的主要活动中是否存在这样的互联网连接。一旦互联网(数据)连接失败,它将正确显示错误。
但是当我退出应用程序并打开互联网连接并运行应用程序时,它也会显示相同的对话框(“没有互联网连接”),当我重新安装应用程序或重新启动设备时它将被清除。
我的代码
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
setFirsLaunchFlag();
cd = new ConnectionDetector(getApplicationContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
TextView text = (TextView) findViewById(R.id.loads);
text.setText("Internet connection error.");
return;
}
...
}
我对android很新..请帮帮我
更新
boolean connected = false;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.login_layput);
ConnectivityManager connectivityManager =
(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
//we are connected to a network
connected = true;
}
else
connected = false;
if(connected==false){
TextView text = (TextView) findViewById(R.id.loads);
text.setText("Internet connection error.");
return;
}
...
}
答案 0 :(得分:1)
使用此代码。
boolean connected = false;
ConnectivityManager connectivityManager =
(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
//we are connected to a network
connected = true;
}
else
connected = false;
使用权限
“android.permission.ACCESS_NETWORK_STATE”
答案 1 :(得分:1)
public static boolean hasInternet(Activity a)
{
try {
boolean hasConnectedWifi = false;
boolean hasConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) a.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("wifi"))
if (ni.isConnected())
hasConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("mobile"))
if (ni.isConnected())
hasConnectedMobile = true;
}
return hasConnectedWifi || hasConnectedMobile;
}
catch (Exception ex) {
}
return false;
}
使用此方法检查您是否有互联网连接...如果有互联网,此方法将返回布尔值true,如果没有互联网则返回false