AsyncTask的正确实现方式是什么?使用静态还是非静态嵌套类?

31

这段文本涉及编程相关内容,讨论了在Android中如何正确实现AsyncTask。Google的“登录”示例使用非静态内部类实现AsyncTask。然而,根据Commonsguys的说法,这个类应该是静态的,并使用外部活动的弱引用参见此处

那么,实现AsyncTask的正确方式是静态还是非静态?

Commonsguy的实现
https://github.com/commonsguy/cw-android/tree/master/Rotation/RotationAsync/

Google的登录示例

package com.example.asynctaskdemo;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class LoginActivity extends Activity {
    /**
     * A dummy authentication store containing known user names and passwords.
     * TODO: remove after connecting to a real authentication system.
     */
    private static final String[] DUMMY_CREDENTIALS = new String[] { "foo@example.com:hello", "bar@example.com:world" };

    /**
     * The default email to populate the email field with.
     */
    public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";

    /**
     * Keep track of the login task to ensure we can cancel it if requested.
     */
    private UserLoginTask mAuthTask = null;

    // Values for email and password at the time of the login attempt.
    private String mEmail;
    private String mPassword;

    // UI references.
    private EditText mEmailView;
    private EditText mPasswordView;
    private View mLoginFormView;
    private View mLoginStatusView;
    private TextView mLoginStatusMessageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);

        // Set up the login form.
        mEmail = getIntent().getStringExtra(EXTRA_EMAIL);
        mEmailView = (EditText) findViewById(R.id.email);
        mEmailView.setText(mEmail);

        mPasswordView = (EditText) findViewById(R.id.password);
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });

        mLoginFormView = findViewById(R.id.login_form);
        mLoginStatusView = findViewById(R.id.login_status);
        mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

        findViewById(R.id.sign_in_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                attemptLogin();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.activity_login, menu);
        return true;
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    public void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }

        // Reset errors.
        mEmailView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        mEmail = mEmailView.getText().toString();
        mPassword = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password.
        if (TextUtils.isEmpty(mPassword)) {
            mPasswordView.setError(getString(R.string.error_field_required));
            focusView = mPasswordView;
            cancel = true;
        }
        else if (mPassword.length() < 4) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = true;
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(mEmail)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        }
        else if (!mEmail.contains("@")) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        }

        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        }
        else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
            showProgress(true);
            mAuthTask = new UserLoginTask();
            mAuthTask.execute((Void) null);
        }
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mLoginStatusView.setVisibility(View.VISIBLE);
            mLoginStatusView.animate().setDuration(shortAnimTime).alpha(show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });

            mLoginFormView.setVisibility(View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });
        }
        else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO: attempt authentication against a network service.

            try {
                // Simulate network access.
                Thread.sleep(2000);
            }
            catch (InterruptedException e) {
                return false;
            }

            for (String credential : DUMMY_CREDENTIALS) {
                String[] pieces = credential.split(":");
                if (pieces[0].equals(mEmail)) {
                    // Account exists, return true if the password matches.
                    return pieces[1].equals(mPassword);
                }
            }

            // TODO: register the new account here.
            return true;
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mAuthTask = null;
            showProgress(false);

            if (success) {
                finish();
            }
            else {
                mPasswordView.setError(getString(R.string.error_incorrect_password));
                mPasswordView.requestFocus();
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
            showProgress(false);
        }
    }
}

如果这取决于特定的情况,那么使用HttpClient从互联网加载ListView项(文本+位图),我应该如何实现我的AsyncTask?
4个回答

18

没有一种“正确”的实现AsyncTask的方式。但这是我的建议:

这个类旨在在Activity的上下文中执行“轻量级”工作。这就是为什么它有onPreExecuteonProgressUpdateonPostExecute方法在UI线程中运行,以便它们可以快速访问字段并更新GUI。任何可能需要更长时间完成且不打算更新特定活动的任务都应该移动到Service中。

这些方法大多用于更新GUI。由于GUI与Activity实例相关(字段可能声明为私有成员变量),因此将AsyncTask实现为非静态嵌套类更方便。在我看来,这也是最自然的方式。

如果任务将在其他活动中重复使用,我认为应该允许它拥有自己的类。说实话,我不喜欢静态嵌套类,尤其是在视图内部。如果它是一个类,意味着它在概念上与活动不同。而且如果它是静态的,意味着它与活动的具体实例无关。但由于它们是嵌套的,这些类在视觉上位于父类内部,使得阅读更加困难,并且在项目包资源管理器中可能被忽略,因为它只显示文件。尽管与内部类相比耦合度较低,但这并不真正有用:如果类发生变化,您必须将整个父文件合并/提交到版本控制中。如果要重用它,则必须在任何地方访问它作为Parent.Nested。因此,为了不将其他活动与Parent类耦合,您可能希望对其进行重构,并将嵌套类提取到自己的文件中。

所以对我来说,问题就是内部类 vs 顶层类


14

一般来说,我会建议使用静态实现(虽然两种方法都可以接受)。

Google的方法需要更少的代码,但是您的asynctask会与您的activity紧密耦合在一起(这意味着不容易重复使用)。但是有时这种方法更易读。

采用CommonsGuy的方法需要更多的努力(和更多的代码)才能解耦activity和asynctask,但最终您将拥有一个更模块化、更可重用的代码。


2
据我理解,非静态嵌套类会在类外保留对其的引用。如果用户在线程池中仍有多个任务排队的情况下突然取消当前活动(按下返回按钮),那么这种方法(非静态)是否会潜在地造成内存泄漏,因为 GC 将无法回收该活动的内存。我理解得对吗?顺便说一句,非常感谢。 - roxrook
2
@Chan AsyncTasks很容易泄漏,包括内部和静态嵌套的AsyncTasks。如果设备更改配置并重新创建活动,则很容易忘记取消旧任务,然后它会在后台继续运行。 - Mister Smith
1
@MisterSmith:谢谢。那么还有其他替代方法吗? - roxrook

3
链接的文章已经说明了这一点。
但是,这强调了你希望AsyncTask的doInBackground()与Activity完全解耦。如果您只在主应用程序线程上触摸Activity,则您的AsyncTask可以在方向更改的情况下保持完整。
不要从AsyncTask中触摸Activity(例如其成员),这符合静态嵌套类的规定
正如类方法和变量一样,静态嵌套类与其外部类相关联。并且像静态类方法一样,静态嵌套类不能直接引用其封闭类中定义的实例变量或方法 - 它们只能通过对象引用使用它们。
尽管Android的示例、AsyncTask参考使用AsyncTask仍在使用非静态嵌套类。

根据这个 Java中的静态嵌套类,为什么?,我会首先选择 静态 内部类,并只在真正需要时使用非静态版本。


1
我发现,在需要频繁更新UI的情况下,非静态嵌套的Asynctask UI更新速度更快,可以通过在onProgressUpdate中调用runOnUiThread来实现。例如,当您需要向TextView追加行时。
non-static:
    @Override
    protected void onProgressUpdate(String... values) {
        runOnUiThread(() -> {
            TextView tv_results = findViewById(R.id.tv_results);
            tv_results.append(values[0] + "\n");
        });
    }

它比为静态AsyncTask实现监听器快1000倍。我可能错了,但这是我的经验。

static:
        @Override
        protected void onProgressUpdate(String... values) {
            OnTaskStringUpdatedListener.OnTaskStringUpdated(task, values[0]);
        }

1
onProgressUpdate 只在UI线程中运行。那么为什么需要 runOnUiThread() 呢? - Hanif

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接