Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

網絡連接狀態判斷與異常處理工具類

編輯:關於 Android 開發

判斷網絡與引導設置

幾乎每個需要联网的 App 都離不開網絡狀態的判斷。下面這個工具類封裝了兩個常用功能:一是判斷當前網絡是否可用,二是在網絡異常時彈出對話框引導用戶去設置。

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();
}
}

isNetworkConnected 方法通過 ConnectivityManager 獲取當前的 NetworkInfo 並判斷是否可用;alertSetNetwork 方法則在檢測到網絡異常時彈出提示框,用戶點擊「設置」會跳轉到系統的網絡設置頁面(代碼中已針對不同 SDK 版本做了兼容處理),點擊「取消」則關閉應用。這樣一來,網絡異常的引導流程就變得清晰而友好了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved