简体   繁体   English

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

[英]Call Async task from start of activity in android

I have a Async task like this in my app: 我的应用程式中有一个类似Async的工作:

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

and calling this in onCreate() method 并在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();
   }

I am running this as soon as user login activity distroyed. 用户登录活动遭到破坏后,我将立即运行它。 that's why I need to call this on onCreate() method. 这就是为什么我需要在onCreate()方法上调用它。 But I am getting this error when the call this in onCreate() method 但是在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)

is there any other event where I can call this? 还有其他活动可以打电话吗? or what I am doing wrong? 还是我做错了什么?

You Forget to call pDialog.dismiss(); 您忘记调用pDialog.dismiss();。 in onPostExecute method of Async task 在异步任务的onPostExecute方法中

Your asyncTask must be like this.After see your code it may possible that You may forgot some method of AsyncTask.Compare with this example to better understand. 您的asyncTask必须是这样的。看完您的代码后,您可能会忘记一些AsyncTask的方法了,请与本示例进行比较以更好地理解。

This is complete example of 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]);

    }
}

call like this: 像这样打电话:

new AsyncTaskRunner (this).execute();

you can use thread policy for this. 您可以为此使用线程策略。 It's work great. 很好 Just add two line below setcontent. 只需在setcontent下添加两行。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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