当互联网不可用时,应用程序崩溃

时间:2014-01-08 07:20:50

标签: android

private void sendPostRequest(String lo, String la, String username,
                String batlevel) {

            class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
               @Override
                protected String doInBackground(String... params) {

                    String lo = params[0];
                    String la = params[1];
                    String username = params[2];
                    String b_level = params[3];

                    System.out.println("*** doInBackground ** paramUsername " + lo
                            + " paramPassword :" + la + "Username" + username
                            + "BatLevel" + b_level);

                    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(
                            "http://gateway.ceylonlinux.com/Ceylon_Steel/service/markGPSLocation");
           BasicNameValuePair longtiude = new BasicNameValuePair(
                            "latitude", lo);
                    BasicNameValuePair lattiude = new BasicNameValuePair(
                            "longitude", la);
                    BasicNameValuePair username_param = new BasicNameValuePair(
                            "userName", username);
                    BasicNameValuePair batery_level = new BasicNameValuePair(
                            "batteryLevel", b_level);

                    // We add the content that we want to pass with the POST request
                    // to as name-value pairs
                    // Now we put those sending details to an ArrayList with type
                    // safe of NameValuePair
                    List<BasicNameValuePair> nameValuePairList = new ArrayList();
                    nameValuePairList.add(longtiude);
                    nameValuePairList.add(lattiude);
                    nameValuePairList.add(username_param);
                    nameValuePairList.add(batery_level);

                    try {
                    UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(
                                nameValuePairList);


                        httpPost.setEntity(urlEncodedFormEntity);

                        try {

                            HttpResponse httpResponse = httpClient
                                    .execute(httpPost);

                            // According to the JAVA API, InputStream constructor do
                            // nothing.
                            // So we can't initialize InputStream although it is not
                            // an interface
                            InputStream inputStream = httpResponse.getEntity()
                                    .getContent();

                            InputStreamReader inputStreamReader = new InputStreamReader(
                                    inputStream);

                            BufferedReader bufferedReader = new BufferedReader(
                                    inputStreamReader);

                            StringBuilder stringBuilder = new StringBuilder();

                            String bufferedStrChunk = null;

                            while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
                                stringBuilder.append(bufferedStrChunk);
                            }
                            return stringBuilder.toString();

                        } catch (ClientProtocolException cpe) {

                            cpe.printStackTrace();
                        } catch (IOException ioe) {

                            ioe.printStackTrace();
                        }

                    } catch (UnsupportedEncodingException uee) {

                        uee.printStackTrace();
                    }

                    return null;
                }

                @Override
                protected void onPostExecute(String result) {
                    super.onPostExecute(result);

                    //
                    Log.i("Result", result);

                }
            }

                SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
            sendPostReqAsyncTask.execute(lo, la, username, batlevel);

在上面的代码我用来向服务器发送数据。如果互联网突然停止,而数据是sedning我得到以下错误并让应用程序崩溃。所以我需要做防止应用程序崩溃。你告诉我如何该

01-08 12:30:42.811: W/System.err(6285): java.net.SocketException: recvfrom failed: ETIMEDOUT (Connection timed out)
01-08 12:30:42.831: W/System.err(6285):     at 

6 个答案:

答案 0 :(得分:3)

您可以检查是否有互联网连接

public boolean isConnectingToInternet(){
    try{
          ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
          if (connectivity != null)
          {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null)
                  for (int i = 0; i < info.length; i++)
                      if (info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return true;
                      }

          }
    }
    catch(Exception e){}
      return false;
}

答案 1 :(得分:1)

使用try catch并捕获异常ConnectTimeoutException并在那里显示所需的结果。

答案 2 :(得分:1)

在调用sendPostRequest()方法之前检查Internet。

此方法检查移动设备是否已连接到互联网,如果已连接则返回true:

private boolean isNetworkConnected() {
  ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo ni = cm.getActiveNetworkInfo();
  if (ni == null) {
   // There are no active networks.
   return false;
  } else
   return true;
 }
清单中的

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

答案 3 :(得分:0)

你的问题有自己的答案。你得到一个SocketException所以处理该异常。处理它的最好方法是在最后添加一个catch子句来处理所有异常。示例代码:

     catch (ClientProtocolException cpe) {

                        cpe.printStackTrace();
                    } catch (IOException ioe) {

                        ioe.printStackTrace();
                    }

                } catch (UnsupportedEncodingException uee) {

                    uee.printStackTrace();
                }

   catch(Exception e)
   {
     //You got a error, diaplay error msg to user here
   }

将该代码放在最后,应该没问题。

答案 4 :(得分:0)

我使用以下代码检查我的Internet连接是否正常工作。

public abstract class NetworkUtils {

    public static boolean isNetworkConnected(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        return networkInfo != null && networkInfo.isConnected();
    }
}

您需要在AndroidManifest.xml中定义以下权限

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

答案 5 :(得分:0)

 increase socket timed out
     // connection timeout, in milliseconds (waiting to connect)
        private static final int CONN_TIMEOUT = 8000;

        // socket timeout, in milliseconds (waiting for data)
        private static final int SOCKET_TIMEOUT = 10000;