从android中的活动开始调用异步任务

时间:2016-08-29 11:20:39

标签: java android asynchronous android-activity

我在我的应用中有这样的异步任务:

 private class getUserSummary extends AsyncTask<String, String, JSONObject> {

    private ProgressDialog pDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(DashboardActivity.this);
        pDialog.setMessage("Getting sales summary...");
        //pDialog.setTitle("Getting sales summary...");
        pDialog.setIndeterminate(true);
        pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected JSONObject doInBackground(String... strings) {
        String JsonResponse = null;
        String JsonDATA = "email=my email address";

        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;
        try {
            ServiceUrl smf = new ServiceUrl();
            URL url = new URL(smf.getUserSummaryUrl());
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);
            // is output buffer writter
            urlConnection.setRequestMethod("GET");
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

            //set headers and method
            Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
            writer.write(JsonDATA);
            // json data
            writer.close();

            int responseCode = urlConnection.getResponseCode();
            if (responseCode == 400) {
                InputStream inputResponse = urlConnection.getErrorStream();
                reader = new BufferedReader(new InputStreamReader(inputResponse));
                StringBuffer errorBuffer = new StringBuffer();
                String errorLine;
                while ((errorLine = reader.readLine()) != null) {
                    errorBuffer.append(errorLine + "\n");
                }
                Log.i("Error text", errorBuffer.toString());
                return new JSONObject(errorBuffer.toString());
            }
            //Log.i("Response code", String.valueOf(inputStream));

            InputStream inputStream = urlConnection.getInputStream();
            //input stream
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                // Nothing to do.
                return null;
            }

            reader = new BufferedReader(new InputStreamReader(inputStream));

            String inputLine;
            while ((inputLine = reader.readLine()) != null)
                buffer.append(inputLine + "\n");
            if (buffer.length() == 0) {
                // Stream was empty. No point in parsing.
                return null;
            }
            JsonResponse = buffer.toString();
            //response data
            Log.i("RESPONSE", JsonResponse);

            return new JSONObject(JsonResponse);

        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e("ERROR", "Error closing stream", e);
                }
            }
        }
        return null;
    }

    protected void onPostExecute(JSONObject result) {
        pDialog.dismiss();
        //post operation here
    }
}

并在onCreate()方法中调用它

        @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dashboard);

    ButterKnife.bind(this);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    initCollapsingToolbar();


    new getUserSummary().execute();
   }

一旦用户登录活动被破坏,我就会运行它。这就是我需要在onCreate()方法上调用它的原因。但是当我在onCreate()方法中调用它时,我收到此错误

android.view.WindowLeaked: Activity softlogic.computers.softlogicsalesreward.DashboardActivity has leaked window com.android.internal.policy.PhoneWindow$DecorView{5329b90 V.E...... R......D 0,0-1002,348} that was originally added here
    at android.view.ViewRootImpl.<init>(ViewRootImpl.java:603)
    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:326)
    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:109)
    at android.app.Dialog.show(Dialog.java:505)
    at softlogic.computers.softlogicsalesreward.DashboardActivity$getUserSummary.onPreExecute(DashboardActivity.java:88)
    at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:604)
    at android.os.AsyncTask.execute(AsyncTask.java:551)
    at softlogic.computers.softlogicsalesreward.DashboardActivity.onResume(DashboardActivity.java:65)
    at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1287)
    at android.app.Activity.performResume(Activity.java:7015)
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4210)
    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4323)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3426)
    at android.app.ActivityThread.access$1100(ActivityThread.java:229)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:7325)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

还有其他任何我可以打电话的事件吗?或者我做错了什么?

3 个答案:

答案 0 :(得分:0)

你忘了打电话给pDialog.dismiss(); 在异步任务的onPostExecute方法

答案 1 :(得分:0)

你的asyncTask必须是这样的。看到你的代码后,你可能会忘记AsyncTask的一些方法。比较这个例子以便更好地理解。

这是asyncTask的完整示例:

private class AsyncTaskRunner extends AsyncTask<String, String, String> {

    private String resp;
    ProgressDialog progressDialog;

    @Override
    protected String doInBackground(String... params) {
        publishProgress("Sleeping..."); // Calls onProgressUpdate()
        try {
            int time = Integer.parseInt(params[0])*1000;

            Thread.sleep(time);
            resp = "Slept for " + params[0] + " seconds";
        } catch (InterruptedException e) {
            e.printStackTrace();
            resp = e.getMessage();
        } catch (Exception e) {
            e.printStackTrace();
            resp = e.getMessage();
        }
        return resp;
    }


    @Override
    protected void onPostExecute(String result) {
        // execution of result of Long time consuming operation
        progressDialog.dismiss();
        finalResult.setText(result);
    }


    @Override
    protected void onPreExecute() {
        progressDialog = ProgressDialog.show(MainActivity.this,
                "ProgressDialog",
                "Wait for "+time.getText().toString()+ " seconds");
    }


    @Override
    protected void onProgressUpdate(String... text) {
        finalResult.setText(text[0]);

    }
}

这样打电话:

new AsyncTaskRunner (this).execute();

答案 2 :(得分:0)

您可以使用线程策略。这很棒。 只需在setcontent下面添加两行。

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
     .detectAll()
     .penaltyLog()
     .build();
 StrictMode.setThreadPolicy(policy);