异步任务运行不正常

时间:2013-01-09 12:45:26

标签: android android-intent android-asynctask android-progressbar

当用户按下“b”按钮时,我使用了Async任务发送邮件,但是显示错误且错误为“Error while executing doInBackground”和“First Activity has leaked a Window

    public class FirstActivity extends Activity implements OnClickListener
    {
    Button b;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b=(Button)findViewById(R.id.button);
        b.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;

    }

    @Override
    public void onClick(View v) {

        ProgressDialog progress = new ProgressDialog(this);
          progress.setMessage("Loading...");
          new MyTask(progress).execute();


        Intent i=new Intent(this,newclass.class);
        startActivity(i);
            }


        // TODO Auto-generated method stub


    public class MyTask extends AsyncTask<Void, Void, Void> {
          private ProgressDialog progress;

        public MyTask(ProgressDialog progress) 
        {
            this.progress = progress;

        }
          public void onPreExecute()
          {

              super.onPreExecute();
              progress.show();

          }

          public Void doInBackground(Void... unused)
          {

              String detail="sending mmail";
              new MainActivity(detail);
            return null;
          }

          public void onPostExecute(Void unused) 
          {
            progress.dismiss();

          }
        }


}

3 个答案:

答案 0 :(得分:1)

尝试在doInBackground中使用此方法......

    public Void doInBackground(Void... unused)
      {
                   runOnUiThread(new Runnable()
            {

                public void run() 
                                    {
                    // TODO Auto-generated method stub

          String detail="sending mmail";
          new MainActivity(detail);
        return null;
                }
            });

      }

答案 1 :(得分:0)

错误是因为您在开始进度对话框后立即开始新活动(对话框丢失其上下文)。 您需要将其移动到onPostExecute()。

public void onPostExecute(Void unused){
    progress.dismiss();
    Intent i = new Intent(this,newclass.class);
    startActivity(i);
}

答案 2 :(得分:0)

您正试图导航到新的ActivityMainActivity,同时ProgressDialog仍处于启用状态。这导致内存泄漏。