简体   繁体   中英

How to finish Activity from AsyncTask Android

In my Application I have 3 Activities:

1. Login

2. AsyncTask (different class)

3. Welcome

After receiving all the information in the Login Activity it moves to the AsyncTask Activity . When the the AsyncTask is completed it moves to the Welcome Activity . I want to close the Login Activity as soon as the AsyncTask Activity completes its job..

I am trying to use the following code in the onPostExecite() of AsyncTask :

Login.this.finish();

But I am getting an error of: No enclosing instance of the type of Login is accessible in scope ..

Please tell me how can i close my Login Activity after completing my AsyncTask ..

Thanks in Advance...

As AsyncTaskActivity is in separate file than LoginActivity, you cant finish LoginActivity by:

Login.this.finish();

Instead you should pass the Activity Reference as parameter in the AsyncTaskActivity Class, like you can define following constructor:

private class AsyncTaskActivity extends AsyncTask<String, Void, String> {

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

and whenever you want to finish the activity call

this.mActivity.finish();

Create AsyncTaskActivity's Object in LoginActivity by

AsyncTaskActivity asynTask = new AsyncTaskActivity(LoginActivity.this);

Ok . you should call finish() in onPostExcecute method after stating new activity.

STEPS:

1) Login activity

2) Asynac Task(pass application context)

3) Call new Activity

4) finish your login activity in onPostExcecute( context.finish())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM