使用AsyncTask开始活动

我正在使用asyncTask来显示对话框,然后几分钟后启动一个新的活动。

不幸的是,活动开始之前任务完成?

package com.android.grad; import android.app.Activity; import android.app.ProgressDialog; import android.os.AsyncTask; import android.widget.Toast; public class LoginTask extends AsyncTask<Void, Void, Boolean> { private Activity activity; private ProgressDialog pd; public LoginTask(Activity activity) { this.activity = activity; } @Override protected void onPreExecute() { pd = ProgressDialog.show(activity, "Signing in", "Please wait while we are signing you in.."); } @Override protected Boolean doInBackground(Void... arg0) { try { Thread.sleep(10000000); } catch (InterruptedException e) { } pd.dismiss(); return true; } @Override protected void onPostExecute(Boolean result) { Toast.makeText(activity, Boolean.toString(result), Toast.LENGTH_LONG).show(); } 

}

我从button点击侦听器执行任务:S

 private OnClickListener loginOnClick = new OnClickListener() { public void onClick(View v) { new LoginTask(LoginActivity.this).execute(); startActivity(new Intent(LoginActivity.this, BuiltInCamera.class)); } }; 

有没有办法从我的子类AsyncTask startActivity。

是的,你可以从AsyncTask的子类开始活动。 见下文:

 @Override protected void onPostExecute(Boolean result) { Toast.makeText(activity, Boolean.toString(result), Toast.LENGTH_LONG).show(); activity.startActivity(new Intent(activity, BuiltInCamera.class)); } 

做这个改变后,确保你从OnClickListener删除了startActivity

调用这个startActivity(new Intent(LoginActivity.this, BuiltInCamera.class));onPostExecute()显示Toast消息后。

这样,在AsyncTask结束之后,将会调用新的活动。

你也可以使用

  Intent intent = new Intent(activity, PageViewActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); activity.getApplicationContext().startActivity(intent); 

AsyncTask onPostExecute方法内调用startActivity