简体   繁体   中英

AsyncTask loading data in very different amount of times in android

I wrote this code to send request and get data from server. Sometimes the loading process takes 2 seconds with 2G internet connection but sometimes it takes more than 20 seconds with 4G internet connection. do i have to consider anything that i did not ?

here is my code

 @Override
protected void onPreExecute() {
    dialog.show();

    new CountDownTimer(10000, 10000) {
        public void onTick(long millisUntilFinished) {
        }

        public void onFinish() {
            // stop async task if not in progress
            if (getStatus() == Status.RUNNING) {
                Request.this.cancel(false);
                activity.finish();
                font.toast(activity.getResources().getString(R.string.connection_problem));

            }
        }
    }.start();

    super.onPreExecute();
}

@Override
protected String doInBackground(String... params) {
    if (isOnline())
        try {

            data += params[1];
            link += params[0];


            URL url = new URL(link);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.connect();

            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(httpURLConnection
                    .getOutputStream()));
            writer.write(data);
            writer.flush();

            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode == 200) {//if valid, read result from server
                BufferedReader reader = new BufferedReader(new InputStreamReader
                        (httpURLConnection.getInputStream()));
                String line;
                StringBuilder stringBuilder = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                return stringBuilder.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    else {
        dialog.cancel();
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                font.toast(activity.getResources().getString(R.string.internet_connection_problem));
                activity.finish();
            }
        });

    }
    return null;
}


@Override
protected void onPostExecute(final String o) {
    try {
        if (o != null) {
            dialog.cancel();
            callBack.onResponse(new Response(o));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    super.onPostExecute(o);
}
 public static boolean isOnline() {
    try {
        int timeoutMs = 2500;
        Socket sock = new Socket();
        SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 53);

        sock.connect(sockaddr, timeoutMs);
        sock.close();

        return true;
    } catch (IOException e) {
        return false;
    }
}

I use post method to send the request to server(php) and then i receive the result.

I Check the internet connection with isOnline method and i set a timeout with CountDownTimer in the onPerExecute method.

is there anyway to speed up the connection ? how do i prevent having very different amount of loading time ?

Just a suggestion here, of course you can ignore me always :)

Why do not use Retrofit -> https://square.github.io/retrofit/ , it is really easy and intuitive.

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