现在一些应用都需要联网,所以在应用启动时检测下联网状况是很必要的,不仅能够增强用户体验度,而且还能应用在没有联网的情况下发生一些错误。下面贴出的代码就是用来检测的网络连接情况的方法:
private boolean checkNetWorkStatus() { //该方法用来检测网络的连接情况,返回TRUE说明已联网
boolean netSataus = false;
ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
cwjManager.getActiveNetworkInfo();
if (cwjManager.getActiveNetworkInfo() != null) {
netSataus = cwjManager.getActiveNetworkInfo().isAvailable();
}
return netSataus;
}
protected void dialog(){//该方法用来检测出没有联网的情况弹出提示信息
AlertDialog.Builder builder=new Builder(TipForTravel.this);
builder.setTitle("提示");
builder.setMessage("网络未连接");
builder.setPositiveButton("设置网络", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which)
{
//下面的这一段代码用来进入无线网络设置页面
Intent intent = new Intent("/");
ComponentName cm = new ComponentName("com.android.settings","com.android.settings.WirelessSettings");
intent.setComponent(cm);
intent.setAction("android.intent.action.VIEW");
startActivityForResult( intent , 0);
dialog.dismiss();
finish();
}
});
builder.setNegativeButton("退出", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which)
{
//下面的代码用来退出应用
dialog.dismiss();
finish();
}
});
builder.create().show();
}
在应用中的使用:
if(!checkNetWorkStatus())
{
dialog();
}