Check Whether Internet Connection is available or not?

前端 未结 3 1581
北恋
北恋 2021-02-06 10:30

I am working on online app. [Problem] when internet is down or not available it gives me error [Force close], I tried to handle using broadCast Receiver but not meet exact solut

3条回答
  •  一个人的身影
    2021-02-06 10:53

    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 nameValuePairs = new ArrayList();
            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;
        }
    

    call this method in your doInBackground() of asyntask, and onPostExecute() check isNetError value and as mentioned in other answer of adding permission

    if(isNetError)
    //No internet 
    else
    //do your stuff
    

提交回复
热议问题