如何防止应用程序在wifi连接丢失时崩溃

时间:2016-03-14 09:28:49

标签: java android json web-services android-wifi

寻找了很多建议,但无法找到适合我的建议。

  

我正在执行网络服务电话:

/**
 * Making service call
 */
private String makeWebServiceCall(String urlAddress, int requestMethod, String params) {
    String response = "";
    HttpURLConnection urlConnection;
    try {
        urlConnection = getConnection(urlAddress, requestMethod);
        urlConnection.connect();
        writeParameters(urlConnection, params);
        response = convertStreamToString(urlConnection);
        Log.d("makeWebServiceCall : ", response);
    } catch (Exception e) {
        //response = "Failed to connect";
        Log.d("makeWebServiceCall ", response);
        Log.e(TAG, "IOException parsing to json", e);
    }
        return response;
}

private HttpURLConnection getConnection(String urlAddress, int requestMethod) throws IOException {


    URL url = new URL(urlAddress);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    try {
        urlConnection.setReadTimeout(3000);
        urlConnection.setConnectTimeout(3000);
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);

        if (requestMethod == POST) {
            urlConnection.setRequestMethod("POST");
        } else if (requestMethod == GET) {
            urlConnection.setRequestMethod("GET");
        }

    } catch (Exception e) {
        new AlertDialog.Builder(context)
                .setIcon(R.drawable.launcher_logo)
                .setTitle("No internet connection")
                .setMessage("Please turn on mobile data");
    }

    return urlConnection;
}

private String writeParameters(HttpURLConnection connection, String jsonString) throws IOException {

    if (!TextUtils.isEmpty(jsonString)) {

        OutputStream outputstream = connection.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(
                new OutputStreamWriter(outputstream, "UTF-8"));

        bufferedWriter.write(jsonString);

        bufferedWriter.flush();
        bufferedWriter.close();
        outputstream.close();

        return jsonString;

    } else {
        return "JSONString is empty";
    }
}

private String convertStreamToString(HttpURLConnection connection) throws IOException {
    String responseLine = "";

    int responseCode = connection.getResponseCode();

    if (responseCode == HttpsURLConnection.HTTP_OK) {
        String line;

        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        while ((line = br.readLine()) != null) {
            responseLine += line;
        }
    }
    return responseLine;
}

当连接丢失时,我得到异常" IOException解析为json":

  

logcat的:

     

E / RestClient:解析为json的IOException                                                  java.net.SocketTimeoutException:3000ms后无法连接到/192.168.1.1(端口80)                                                      在libcore.io.IoBridge.connectErrno(IoBridge.java:169)                                                      在libcore.io.IoBridge.connect(IoBridge.java:122)                                                      在java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)                                                      在java.net.PlainSocketImpl.connect(PlainSocketImpl.java:452)                                                      在java.net.Socket.connect(Socket.java:884)                                                      在com.android.okhttp.internal.Platform.connectSocket(Platform.java:117)                                                      在com.android.okhttp.internal.http.SocketConnector.connectRawSocket(SocketConnector.java:160)                                                      在com.android.okhttp.internal.http.SocketConnector.connectCleartext(SocketConnector.java:67)                                                      在com.android.okhttp.Connection.connect(Connection.java:152)                                                      在com.android.okhttp.Connection.connectAndSetOwner(Connection.java:185)                                                      在com.android.okhttp.OkHttpClient $ 1.connectAndSetOwner(OkHttpClient.java:128)                                                      在com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:341)                                                      在com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)                                                      在com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)                                                      在com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:437)                                                      在com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)                                                      在com.example.pc.teltonikaapplication.JSon.RestClient.makeWebServiceCall(RestClient.java:118)                                                      at com.example.pc.teltonikaapplication.JSon.RestClient.deviceDownloadUploadData(RestClient.java:73)                                                      在com.example.pc.teltonikaapplication.fragment.MainWindowFragment.doInBackground(MainWindowFragment.java:107)                                                      at com.example.pc.teltonikaapplication.fragment.MainWindowFragment.doInBackground(MainWindowFragment.java:28)                                                      在com.example.pc.teltonikaapplication.util.Task.doInBackground(Task.java:27)                                                      在android.os.AsyncTask $ 2.call(AsyncTask.java:295)                                                      在java.util.concurrent.FutureTask.run(FutureTask.java:237)                                                      在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)                                                      at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:588)                                                      在java.lang.Thread.run(Thread.java:818)

一切似乎没问题,如果没有连接异常被捕获,但如何处理崩溃以防止它?

1 个答案:

答案 0 :(得分:3)

在我的应用中实施支票后,查看是否有任何互联网连接。你可以看看这个 -

public class ConnectionDetector {

private Context context;

public ConnectionDetector(Context cont){
this.context = cont;
}

public boolean isConnectingToInternet(){
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;
        }
    }
}

}
 return false;
}
}

您可以在OnCreate方法中初始化此类的对象。

最后打电话给这个班级&#39;在您上传文件之前的方法。

Boolean isInternetConnected = cd.isConnectingToInternet();
if (isInternetConnected)
{
    //perform your job here.
}

希望这有帮助。