我在我的Android应用程序中从服务器获取数据,同时检查Internet连接,当没有Internet连接时应用程序崩溃。我使用默认的http连接来连接服务器。
检查互联网连接的代码是:
public void onClick(View view) {
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
//if it is connected to internet than start Another Activity.
startActivity(new Intent(SearchActivity.this, SearchActivity.class));
} else if (netInfo == null) {
AlertDialog alertDialog = new AlertDialog.Builder(ListViewExample.this).create();
alertDialog.setTitle("Connection Problem");
alertDialog.setMessage("You are not connected to Internet");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
}
答案 0 :(得分:1)
确保您已在清单文件中添加此权限,
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
答案 1 :(得分:0)
使用此代码检查互联网连接,检查设备上的所有互联网连接。并且确保你已经在menifest中添加了Internet权限。
boolean flag=false;
ConnectivityManager connectivity = (ConnectivityManager) getApplicationContext().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)
{
flag=true;
}
}
if(flag==true)
{
startActivity(new Intent(SearchActivity.this, SearchActivity.class));
}
else
{
AlertDialog alertDialog = new AlertDialog.Builder(ListViewExample.this).create();
alertDialog.setTitle("Connection Problem");
alertDialog.setMessage("You are not connected to Internet");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}