简体   繁体   中英

How to prevent App from crashing when wifi connection is lost

Looked for a lot of suggestions, but couldn't find one which would fit for me.

I'm executing web service call:

/**
 * 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;
}

When connection is lost I get exception "IOException parsing to json":

logcat:

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

Everything seems OK, if there is no connection Exception is caught, but how to handle crashing from preventing it?

Once I had implemented a check in my app, to see if there is any internet connection or not. You can have a look at this --

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;
}
}

You can initialize an object of this class in your OnCreate method.

And finally call this class' method just before you upload files.

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

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM