使用AsyncTask启动活动

时间:2012-05-24 11:55:43

标签: android android-asynctask

我使用asyncTask显示Dialog,然后几分钟后启动一个新活动。

不幸的是,活动在任务完成之前就开始了

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

}

我从按钮点击监听器执行任务:S

private OnClickListener loginOnClick = new OnClickListener() {

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

有没有办法从我的subClass ofAsyncTask中启动活动。

4 个答案:

答案 0 :(得分:34)

是的,您可以从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

答案 1 :(得分:5)

startActivity

onPostExecute方法中调用AsyncTask

答案 2 :(得分:5)

在显示toast消息后,从startActivity(new Intent(LoginActivity.this, BuiltInCamera.class));调用此onPostExecute()

这样,在AsyncTask结束后,系统会调用新活动。

答案 3 :(得分:5)

您也可以使用

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