带有超时的AsyncTask

时间:2016-03-01 10:17:50

标签: android android-asynctask

我希望我的应用程序在AsyncTask中10秒后抛出超时。所以我该怎么办?如果我没有使用这个,那么我的申请就会崩溃。

抱歉我的英语不好。

这是我的AsyncTask

LoginTask

 public class LoginTask extends AsyncTask<Void, Integer, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progress.setVisibility(View.VISIBLE);

        }

        @Override
        protected Void doInBackground(Void... params) {

        /*  JSONParser jParser = new JSONParser();
            // JSONArray data = null;
            String jsonstr = jParser.makeServiceCall(URL, JSONParser.POST);*/
            BufferingH call = new BufferingH();
            jsonstr = call.makeBufferCall(URL);
            System.out.println("Json url view string  " + jsonstr);

            return null;
        }

        @SuppressLint("ShowToast")
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            if (jsonstr != null) {
                try {
                    JSONObject jobj = new JSONObject(jsonstr);
                    URLmessage = jobj.getString("message").toString();
                    JSONArray jarray = jobj.getJSONArray("Data");

                    for (int i = 0; i < jarray.length(); i++) {
                        JSONObject jobjj = jarray.getJSONObject(i);

                        Username = jobjj.getString("r_name");
                        Password = jobjj.getString("r_password");
                        FirstName=jobjj.getString("first_name");
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(getApplicationContext(), "Invalid username password", Toast.LENGTH_SHORT).show();
                Log.e("Login Screen", "Couldn't get any data from the url");
            }
            try {
                if (URLmessage.matches("Invalid Login")) {
                    Toast.makeText(getApplicationContext(), "Invalid Login.....",
                            Toast.LENGTH_SHORT).show();
                    //              Intent intent = new Intent(Login.this, Register.class);
                    //              startActivity(intent);
                } else {

                    Toast.makeText(getApplicationContext(), "Login Successful...",
                            Toast.LENGTH_SHORT).show();

                    Password = et_password.getText().toString();
                    Username = et_username.getText().toString();

                    Intent k = new Intent(getBaseContext().getApplicationContext(),
                            MainActivity.class);
                    k.putExtra("regId", regId);
                    startActivity(k);
                    finish();

                    SettingsFragment.setDefaults("Username", Username, getApplicationContext());
                    SettingsFragment.setDefaults("Password", Password, getApplicationContext());
                    SettingsFragment.setDefaults("FirstName", Login.FirstName, getApplicationContext());
                    Toast.makeText(getApplicationContext(), "FirstName = "+FirstName, Toast.LENGTH_SHORT).show();

                    //  gcmregister_from_sharedpref
                    gcmafterregistration();
                    overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            progress.setVisibility(View.INVISIBLE);
        }
    }

这是我的logcat,所以你可以理解。

enter image description here

2 个答案:

答案 0 :(得分:2)

我已经通过引用一个虚拟代码来更改代码。

 public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        if (commonUtils.isNetworkAvailable(mContext)) {
            NewHistoryAsync task = new NewHistoryAsync(getContext(), listDataHeader, listDataChild);
            task.execute(CommonUtils._History + "ID=" + userUhid);
        } else {
            Toast.makeText(mContext, "No Network Available!!",
                    Toast.LENGTH_LONG).show();
        }



    private class NewHistoryAsync extends AsyncTask<String, String, String> {
        ProgressDialog progressDialog;
        Context mContext;
        List listDataHeader;
        HashMap listDataChild;

        public NewHistoryAsync(Context context, List listDataHeaderList, HashMap listDataChildMap) {
            mContext = context;
            listDataHeader = listDataHeaderList;
            listDataChild = listDataChildMap;
            this.listDataHeader = new ArrayList<String>();
            this.listDataChild = new HashMap<String, List<String>>();

        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = new ProgressDialog(getActivity());
            progressDialog = ProgressDialog.show(mContext, Html.fromHtml(
                    "<b>Heading<b>"), Html.fromHtml("<medium>Downloading Details..</medium>"), true);

//            progressDialog.setTitle("Downloading Details");
            progressDialog.setCancelable(false);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.show();
        }

        @Override
        protected String doInBackground(String... params) {
            String resResult = NewHistoryService(params[0]);
            JSONObject jsonResponse;

            try {
                //JSONObject jsonObject = new JSONObject(resResult);
                JSONArray jsonArray = new JSONArray(resResult);

               // Log.i("doinb---> ", resResult);
              /*  ArrayList<ClaimsHistoryNewSearchModel> listDataHeader=new ArrayList<ClaimsHistoryNewSearchModel>();*/
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    List<String> historyResult = new ArrayList<String>();
                    historyResult.add((jsonObject.get("AdmissionDate").toString()));
                    historyResult.add((jsonObject.get("DischargeDate").toString()));
                   //AdmissionDate= exact name to ur json response from server


                    listDataHeader.add(KeyString);
                    listDataChild.put(KeyString, historyResult);

                }

            } catch (Exception e) {
                e.printStackTrace();

            }
            return resResult;
        }

        @Override
        protected void onProgressUpdate(String... values) {


            Toast.makeText(mContext, values[0], Toast.LENGTH_SHORT).show();
        }

        @Override
        protected void onPostExecute(String result) {
            if (progressDialog != null && progressDialog.isShowing() == true) {
                progressDialog.dismiss();
                if (result.equals("[]")) {
                    Toast.makeText(mContext, "No Details found!!",
                            Toast.LENGTH_LONG).show();
                } else
//                    Log.i("Result:", result);
//                Log.i("listDataHeader:", listDataHeader.toString());
//                Log.i("listDataChild:", listDataChild.toString());
                listAdapter = new ClaimHistoryNewAdapter(getActivity(), listDataHeader, listDataChild);
                if (listDataHeader != null && listDataHeader.size() > 0 && listDataChild != null && listDataHeader.size() > 0) {
                    expListView.setAdapter(listAdapter);
                } else {
                    // setting list adapter
                    tClaimHistory.setVisibility(View.VISIBLE);
                }
            }
        }

        public String NewHistoryService(String serviceUrl) {

            StringBuffer response = new StringBuffer();
            URL url = null;

            HttpURLConnection conn = null;
            try {

                url = new URL(serviceUrl);
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(30000);
                conn.setDoOutput(false);
                conn.setUseCaches(false);
                conn.setRequestMethod("GET");
                conn.setRequestProperty("Content-Type",
                        "application/x-www-form-urlencoded;charset=UTF-8");
                int status = conn.getResponseCode();
                if (status != 200) {
                    throw new IOException("Post failed with error code " + status);
                }


                // Get Response
                InputStream is = conn.getInputStream();
                BufferedReader rd = new BufferedReader(new InputStreamReader(is));
                String line;

                while ((line = rd.readLine()) != null) {
                    response.append(line);

                }
                rd.close();

            } catch (Exception e) {
                e.printStackTrace();
                //ErrorLogger.writeLog(claimNo, "Error Msg : "+e.getMessage()+"..."+ErrorLogger.StackTraceToString(e), "sendSyncService Failed");
                //response.append("Error");
            }
            Log.v("Response:", response.toString());
            return response.toString();

        }
    }
}

答案 1 :(得分:1)

使用此JsonParser类 希望它能帮到你

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class JSONParser {

    public JSONParser() {

    }

    public String makeServiceCall(String serviceUrl) {
        Boolean registered = false;
        StringBuffer response = new StringBuffer();
        URL url = null;

        HttpURLConnection conn = null;
        try {

            url = new URL(serviceUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(30000);
            conn.setDoOutput(false);
            conn.setUseCaches(false);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset=UTF-8");
            int status = conn.getResponseCode();
            if (status != 200) {
                throw new IOException("Post failed with error code " + status);
            }
            registered = true;

            // Get Response
            InputStream is = conn.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;

            while ((line = rd.readLine()) != null) {
                response.append(line);

            }
            rd.close();

        } catch (Exception e) {
            e.printStackTrace();
        /*  ErrorLogger.writeLog(claimNo, "Error Msg : "+e.getMessage()+"..."+ErrorLogger.StackTraceToString(e), "sendSyncService Failed");
            response.append("Error");*/
        }
        Log.v("Response:", response.toString());
        return response.toString();

    }


}

setConnectionTimeout(您的时间);