Java 异步任务过程

Java 异步任务过程,java,android,multithreading,user-interface,android-asynctask,Java,Android,Multithreading,User Interface,Android Asynctask,我正在创建一个应用程序,当您使用用户名和密码登录时,它会从服务器请求信息。 服务器的请求需要时间(15-20秒),同时我想用几句话来展示一个旋转条。 但是我尝试了太多的AsyncTask类的变体,但我无法让它工作。它可以获得信息,但会冻结屏幕直到收到响应。 现在我有一个新线程实现了runnable。我不确定需要从代码的何处调用异步任务 onClick触发attemptLogin()函数: public void onClick(View view) { attemptLo

我正在创建一个应用程序,当您使用用户名和密码登录时,它会从服务器请求信息。 服务器的请求需要时间(15-20秒),同时我想用几句话来展示一个旋转条。 但是我尝试了太多的
AsyncTask
类的变体,但我无法让它工作。它可以获得信息,但会冻结屏幕直到收到响应。 现在我有一个新线程实现了
runnable
。我不确定需要从代码的何处调用
异步任务

onClick
触发
attemptLogin()
函数:

    public void onClick(View view) {
        attemptLogin();
    }
// more code
showProgress(true);
new Thread(new GetServerResponseRunnable()).start();
while (wait) {}
// more code
public String getTours(String username, String password) {
    String req = "GETALLDATA";
    String retStr = "";
    try {
        url = getURL(req, username, password);
        sendOutputLine(url, "");
        retStr = getReturnString();
        Log.d(LoginActivity.DEBUG_TAG, "getTours() return: " + retStr);
    } catch (Exception e) {
        Log.d(LoginActivity.DEBUG_TAG, "programm bommed client: " + e.getMessage());
    }
    return retStr;
}   
attemptLogin()函数中:

    public void onClick(View view) {
        attemptLogin();
    }
// more code
showProgress(true);
new Thread(new GetServerResponseRunnable()).start();
while (wait) {}
// more code
public String getTours(String username, String password) {
    String req = "GETALLDATA";
    String retStr = "";
    try {
        url = getURL(req, username, password);
        sendOutputLine(url, "");
        retStr = getReturnString();
        Log.d(LoginActivity.DEBUG_TAG, "getTours() return: " + retStr);
    } catch (Exception e) {
        Log.d(LoginActivity.DEBUG_TAG, "programm bommed client: " + e.getMessage());
    }
    return retStr;
}   
可运行的是:

public class GetServerResponseRunnable implements Runnable {
    @Override
    public void run() {
        response = getInfo.getTours(mUsername, mPassword);
        wait = false;   
    }       

}  
正如您所看到的,从不同的类调用另一个函数。 这就是功能:

    public void onClick(View view) {
        attemptLogin();
    }
// more code
showProgress(true);
new Thread(new GetServerResponseRunnable()).start();
while (wait) {}
// more code
public String getTours(String username, String password) {
    String req = "GETALLDATA";
    String retStr = "";
    try {
        url = getURL(req, username, password);
        sendOutputLine(url, "");
        retStr = getReturnString();
        Log.d(LoginActivity.DEBUG_TAG, "getTours() return: " + retStr);
    } catch (Exception e) {
        Log.d(LoginActivity.DEBUG_TAG, "programm bommed client: " + e.getMessage());
    }
    return retStr;
}   
我需要帮助,请。我主要想做的是:

    response = getInfo.getTours(mUsername, mPassword);
    wait = false;
同时展示旋转杆

谢谢


更新:02.13.2013

我用了这个密码,但我得到了一个

02-13 09:07:16.142: E/AndroidRuntime(1046): java.lang.NullPointerException
行中:

this.dialog.setMessage(getResources().getString(R.string.login_progress_signing_in));
知道为什么吗

public class LoginTask extends AsyncTask<Object, Void, String> {

    public Context context;
    public ProgressDialog dialog;


    public void BaseTask(Context context) {
        this.context = context;
        this.dialog = new ProgressDialog(context);
    }

    @Override
    protected void onPreExecute() {
        this.dialog.setMessage(getResources().getString(R.string.login_progress_signing_in));
        this.dialog.show();

    }

    @Override
    protected String doInBackground(Object... objects) {
        String name = (String) objects[0];
        String password = (String) objects[1];
        String response = getInfo.getTours(name , password );
        return response;
    }

    @Override
    protected void onPostExecute(String response) {
        if (dialog != null && dialog.isShowing())
            dialog.dismiss();

        LoginActivity.response = response; 

        // process response as you need
    }
} 
公共类登录任务扩展异步任务{
公共语境;
公共对话;
公共void基任务(上下文){
this.context=上下文;
this.dialog=newprogressdialog(上下文);
}
@凌驾
受保护的void onPreExecute(){
this.dialog.setMessage(getResources().getString(R.string.login\u progress\u signing\u in));
this.dialog.show();
}
@凌驾
受保护的字符串doInBackground(对象…对象){
字符串名称=(字符串)对象[0];
字符串密码=(字符串)对象[1];
String response=getInfo.getTours(名称、密码);
返回响应;
}
@凌驾
受保护的void onPostExecute(字符串响应){
if(dialog!=null&&dialog.isShowing())
dialog.dismise();
LoginActivity.response=响应;
//根据需要处理响应
}
} 

尝试实施android登录活动。 在ADT中的“创建新活动”下,选择“登录活动” 这将为您生成以下模板代码:

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class LoginActivityTest 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_activity_test);

            // 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_activity_test, 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);
            }
        }
    }
/**
*向用户显示登录屏幕的活动,提供注册为
*嗯。
*/
公共类LoginActivityTest扩展活动{
/**
*包含已知用户名和密码的虚拟身份验证存储。
*TODO:连接到真实身份验证系统后删除。
*/
私有静态最终字符串[]伪\u凭据=新字符串[]{
"foo@example.com:你好“bar@example.com:世界“};
/**
*用于填充电子邮件字段的默认电子邮件。
*/
public static final String EXTRA_EMAIL=“com.example.android.authenticatordemo.EXTRA.EMAIL”;
/**
*跟踪登录任务,确保我们可以根据请求取消它。
*/
private UserLoginTask mAuthTask=null;
//尝试登录时的电子邮件和密码值。
私有字符串mEmail;
私有字符串mPassword;
//用户界面引用。
私有编辑文本mEmailView;
私有编辑文本mPasswordView;
私有视图mloginfo视图;
私有视图mLoginStatusView;
私有文本视图mLoginStatusMessageView;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u login\u activity\u test);
//设置登录表单。
mEmail=getIntent().getStringExtra(额外电子邮件);
mEmailView=(EditText)findViewById(R.id.email);
mEmailView.setText(mEmail);
mPasswordView=(EditText)findViewById(R.id.password);
mPasswordView
.setOnEditorActionListener(新的TextView.OnEditorActionListener(){
@凌驾
公共布尔onEditorAction(TextView TextView,int-id,
KeyEvent(关键事件){
if(id==R.id.login | | id==EditorInfo.IME_NULL){
尝试登录();
返回true;
}
返回false;
}
});
mLoginFormView=findviewbyd(R.id.login\u表单);
mLoginStatusView=findviewbyd(R.id.login\u状态);
mLoginStatusMessageView=(TextView)findviewbyd(R.id.login\u status\u message);
findViewById(R.id.sign_in_按钮)。setOnClickListener(
新建视图。OnClickListener(){
@凌驾
公共void onClick(视图){
尝试登录();
}
});
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
super.onCreateOptions菜单(菜单);
getMenuInflater().充气(R.menu.activity\u login\u activity\u test,menu);
返回true;
}
/**
*尝试登录或注册登录表单指定的帐户。
*如果存在表单错误(无效电子邮件、缺少字段等),则
*出现错误,未进行实际登录尝试。
*/
public void attemptLogin(){
if(mAuthTask!=null){
返回;
}
//重置错误。
mEmailView.setError(null);
mPasswordView.setError(null);
//在尝试登录时存储值。
mEmail=mEmailView.getText().toString();
mPassword=mPasswordView.getText().toString();
布尔取消=假;
视图焦点视图=空;
//检查密码是否有效。
if(TextUtils.isEmpty(mPassword)){
mPasswordView.setError(getString(R.string.error_字段_必填));