Android檢測網絡狀態,判斷當前網絡是否可用

public boolean isNetworkAvailable(Activity activity)
{
    Context context = activity.getApplicationContext();
    // 獲取手機全部鏈接管理對象(包括對wi-fi,net等鏈接的管理)
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    if (connectivityManager == null)
    {
        return false;
    }
    else
    {
        // 獲取NetworkInfo對象
        NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

        if (networkInfo != null && networkInfo.length > 0)
        {
            for (int i = 0; i < networkInfo.length; i++)
            {
                System.out.println(i + "===狀態===" + networkInfo[i].getState());
                System.out.println(i + "===類型===" + networkInfo[i].getTypeName());
                // 判斷當前網絡狀態是否爲鏈接狀態
                if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED)
                {
                    return true;
                }
            }
        }
    }
    return false;
}

 

 

 

//        if (isNetworkAvailable(MainActivity.this))
//        {
//            Toast.makeText(getApplicationContext(), "當前有可用網絡!", Toast.LENGTH_LONG).show();
//        }
//        else
//        {
//            Toast.makeText(getApplicationContext(), "當前沒有可用網絡!", Toast.LENGTH_LONG).show();
//        }
相關文章
相關標籤/搜索