网络连接异常处理工具

public class NetStateUtils {


/**
* 对网络连接状态进行判断
*
* @return true, 可用; false, 不可用
*/
public static boolean isNetworkConnected(Context context) {
if (context != null) {
ConnectivityManager connManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
if (networkInfo != null) {
return networkInfo.isAvailable();
}
}
return false;
}


/**
* 提示设置网络连接
*
*/
public static void alertSetNetwork(final Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(context.getResources().getString(R.string.neterror)).setMessage(context.getString(R.string.question));

builder.setPositiveButton(context.getResources().getString(R.string.set), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = null;
try {
int sdkVersion = android.os.Build.VERSION.SDK_INT;
if (sdkVersion > 10) {
intent = new Intent(
android.provider.Settings.ACTION_WIRELESS_SETTINGS);
} else {
intent = new Intent();
ComponentName comp = new ComponentName(
"com.android.settings",
"com.android.settings.WirelessSettings");
intent.setComponent(comp);
intent.setAction("android.intent.action.VIEW");
}
context.startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
});
builder.setNegativeButton(context.getString(R.string.cancle), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
System.exit(0);
System.gc();
}
});
builder.show();
}
}
原文地址:https://www.cnblogs.com/zhou2016/p/5329495.html