方法onPostExecute如何启动新的Activity

时间:2013-03-21 21:03:41

标签: android android-asynctask

我有一个任务执行方法doInBackground并返回一个布尔值。我想要的是启动一个新的Intent但方法startActivity不可用。我怎么能这样做?

我的任务:

        public class LoginTask extends AsyncTask<String, Integer, Boolean> {

            @Override
            protected Boolean doInBackground(String... params) {

                 boolean sucess;

                 //do some stuff

                 return sucess;
            }

    @Override
        protected void onPostExecute(Boolean result) {

            if (result) {
                //startActivity(new Intent(this, MainViewActivity.class));
                            //it doesn't find startActivity
            }
        }
        }

5 个答案:

答案 0 :(得分:3)

在构造函数中传递启动AsyncTak的Activity

public class LoginTask {
    private Context mCtx;

    public LoginTask(Context ctx){
        mCtx = ctx;
    }

    ....

    @Override
    protected void onPostExecute(Boolean result) {
        if (result) {
            mCtx.startActivity(new Intent(mCtx, MainViewActivity.class));
        }
    }
}

答案 1 :(得分:2)

关于先前回复的评论: 请记得不要leak your activity。使用WeakReference类:

public static class LoginTask extends AsyncTask<String, Integer, Boolean> {
    WeakReference<Activity> mActivityReference;

    public LoginTask(Activity activity){
        this.mActivityReference = new WeakReference<Activity>(activity);
    }

    @Override
    protected Boolean doInBackground(String... params) {

         boolean sucess;

         //do some stuff

         return sucess;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        if (result && mActivityReference.get() != null) {
            Activity activity = mActivityReference.get();
            activity.startActivity(new Intent(activity, MainViewActivity.class));
        }
    }
}

答案 2 :(得分:1)

您需要创建任务,并引用生成它的活动或上下文。

public class LoginTask extends AsyncTask<String, Integer, Boolean> {
    Activity mActivity;

    public LoginTask(Activity activity){
        this.mActivity = mActivity;
    }

    @Override
    protected Boolean doInBackground(String... params) {

         boolean sucess;

         //do some stuff

         return sucess;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        if (result) {
            mActivity.startActivity(new Intent(mContext, MainViewActivity.class));
        }
    }
}

答案 3 :(得分:0)

您确定startActivity不可用吗?我刚试过它,它对我来说很好。

我认为您应该替换行中的 this ,因为这不是指Activity,而是指ASyncTask。

   startActivity(new Intent(getApplicationContext(), MainViewActivity.class));

这应该有效。

答案 4 :(得分:0)

onPostExecute()里面的

this是指AsyncTask类的实例。 请改用YourActivityName.this

startActivity(new Intent(ParentActivity.this, MainViewActivity.class));