/** 判断网络是否连接的方法 */
public static boolean isConnection(Context context) {
ConnectivityManager con = (ConnectivityManager) context
.getSystemService(Activity.CONNECTIVITY_SERVICE);
boolean wifi = con.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.isConnectedOrConnecting();
boolean internet = con.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
.isConnectedOrConnecting();
if (wifi || internet) {
// 返回true,说明网络连接可用
return true;
} else {
Toast.makeText(context, "请打开数据流量或无线开关", Toast.LENGTH_LONG).show();
}
return false;
}
常用的工具方法,整理了一下,参数传activity或者application都可以。
然后网络未连接时候调用系统的设置,去连接网路,方法如下:
/**
* 网络未连接时,调用设置方法
*/
public static void setNetwork(final Activity activity) {
Toast.makeText(activity, "wifi is closed!", Toast.LENGTH_SHORT).show();
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setIcon(R.drawable.ic_launcher);
builder.setTitle("网络提示信息");
builder.setMessage("网络不可用,如果继续,请先设置网络!");
builder.setPositiveButton("设置", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = null;
/**
* 判断手机系统的版本!如果API大于10 就是3.0+ 因为3.0以上的版本的设置和3.0以下的设置不一样,调用的方法不同
*/
if (android.os.Build.VERSION.SDK_INT > 10) {
intent = new Intent(
android.provider.Settings.ACTION_WIFI_SETTINGS);
} else {
intent = new Intent();
ComponentName component = new ComponentName(
"com.android.settings",
"com.android.settings.WirelessSettings");
intent.setComponent(component);
intent.setAction("android.intent.action.VIEW");
}
activity.startActivity(intent);
}
});
builder.setNegativeButton("取消", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.create();
builder.show();
}
如果需要判断是wifi还是数据流量,可以在第一个方法里面进行情况的细分类,就不细说了。