-8

当用户按下按钮“b”时,我使用异步任务发送邮件,但它显示错误,错误是“ 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();

          }
        }


}
4

3 回答 3

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

      }
于 2013-01-09T13:01:31.973 回答
0

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

public void onPostExecute(Void unused){
    progress.dismiss();
    Intent i = new Intent(this,newclass.class);
    startActivity(i);
}
于 2013-01-09T12:51:15.753 回答
0

您正在尝试导航到新的Activity, MainActivity,而 ,ProgressDialog仍然打开。这导致内存泄漏。

于 2013-01-09T12:51:44.307 回答