android – 检查Internet连接是否可用?

前端之家收集整理的这篇文章主要介绍了android – 检查Internet连接是否可用?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在开发在线应用程序. [问题]当互联网停机或不可用时,它给我错误[强制关闭],我试图使用broadCast接收器处理但不满足精确解决方案,寻找更好的解决方案.
public class MyBroadcastReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context,final Intent intent) {

    NetworkInfo info = intent
            .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

    if (null != info) {

        String state = info.getState().toString();

        if (state.equalsIgnoreCase("CONNECTED")) {
            SplashScreen.isWiFiConnected = true;
            Log.i("isWifiConnected","=================TRUE");
        } else {
            SplashScreen.isWiFiConnected = false;
            Log.i("isWifiConnected","=================FALSE");
        }

    }

}

}

谢谢.

解决方法

static String data = null;
private static HttpPost httppost;
private static HttpParams httpParameters;
private static int timeoutConnection = 30000;
private static HttpClient httpclient = null;
private static HttpResponse response = null;
private static int responseCode=0;
public static ConnectivityManager mConnectivityManager;
public static NetworkInfo mNetworkInfo;
public static boolean isNetError=false;

/** Post Http data and returns final string and status on network */

public static void postHttp(String Url,Activity mActivity) {
try {
    isNetError=false;

    mConnectivityManager= (ConnectivityManager) mActivity.getSystemService(Context.CONNECTIVITY_SERVICE);
    mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();

    if (mNetworkInfo != null && mNetworkInfo.isConnectedOrConnecting())
    {
        httppost = new HttpPost(Url);
        httpParameters = new BasicHttpParams();
        HttpConnectionParams.setSoTimeout(httpParameters,timeoutConnection);
        httpclient = new DefaultHttpClient(httpParameters);

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("text","some Text"));


        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8));

        // Execute HTTP Post Request
        response = httpclient.execute(httppost);
        data = EntityUtils.toString(response.getEntity());

    }
    else
        isNetError=true;

    } catch (Exception e) {
        e.printStackTrace();
        isNetError=true;
        }

   if (responseCode == 200)
   {
        isNetError=false;
        System.out.println("final..." + data);
        }
        else
            isNetError=true;
    }

在asyntask的doInBackground()中调用方法,并在onPostExecute()中检查isNetError值,并在添加权限的其他答案中提及< uses-permission android:name =“android.permission.ACCESS_NETWORK_STATE”/>

if(isNetError)
//No internet 
else
//do your stuff
原文链接:https://www.f2er.com/android/310563.html

猜你在找的Android相关文章