11

I am using asyncTask to show Dialog and then after few minutes then launch a new activity.

unfortunately that activity start before task finished ???

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

}

and i execute the task from button click listener :S

private OnClickListener loginOnClick = new OnClickListener() {

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

Is there way to startActivity from my subClass ofAsyncTask .

Mahmoud Emam
  • 1,499
  • 4
  • 20
  • 37

4 Answers4

34

Yes, you can start activity from AsyncTask's sub class. See below:

@Override
protected void onPostExecute(Boolean result) {
    Toast.makeText(activity, Boolean.toString(result), Toast.LENGTH_LONG).show();

    activity.startActivity(new Intent(activity, BuiltInCamera.class));
}

After making this change, make sure you do remove startActivity from OnClickListener

waqaslam
  • 67,549
  • 16
  • 165
  • 178
5

Call startActivity inside onPostExecute method of AsyncTask

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
Raghu Nagaraju
  • 3,278
  • 1
  • 18
  • 25
5

Call this startActivity(new Intent(LoginActivity.this, BuiltInCamera.class)); from onPostExecute() after Displaying toast message.

In this way, new activity will be called after your AsyncTask is over.

Verbeia
  • 4,400
  • 2
  • 23
  • 44
Shrikant Ballal
  • 7,067
  • 7
  • 41
  • 61
5

You can also use

    Intent intent = new Intent(activity, PageViewActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    activity.getApplicationContext().startActivity(intent);
  • it works fine but in my try the activity run for tow time - one in new activity ( first line - and second in third line – ehsan wwe Oct 05 '17 at 07:06