在其他线程中收到信息后开始新活动

时间:2013-06-20 16:25:19

标签: android multithreading android-activity

这是我的代码的一部分:单击按钮后,将启动新线程和服务器连接。如果连接成功,应用程序应启动新活动并结束当前。有人可以解释哪种方式最适合这样做?

    transThread.submit(new Runnable()
            {
                public void run()
                {
                    guiProgressDialog(true);
                    if(user.length() < 4) guiNotifyUser("Username must have at least 4 characters!");
                    else if(pass.length() < 4) guiNotifyUser("Password must have at least 4 characters!");
                    else if(!pass.equals(passrtp)) guiNotifyUser("Password is not same in both fields!");
                    else if(!isValidEmail(mail)) guiNotifyUser("Your email is not valid email address!");
                    else if(fname.equals("") || lname.equals("")) guiNotifyUser("All fields are mandatory!");
                    else {
                        try {
                            final String message = AutoDiaryHttpHelper.signUp(user, md5(pass), mail, fname, lname);
                            guiNotifyUser(message);
//if message equals something start new activity

                        }
                        catch(Exception e) {
                            e.printStackTrace();
                        }
                    }
                    guiProgressDialog(false);
                }
            });

            break;

2 个答案:

答案 0 :(得分:3)

您可以使用runOnUiThreadHere is a SO answer显示了如何做到这一点。

我个人喜欢使用AsyncTask。您可以在doInBackground()内完成工作,然后将值返回onPostExecute()并从那里开始Activity或在UI上执行您需要的操作。

AsyncTask Docs

Here is an answer of mine显示了使用AsyncTask

的基本结构和重要细节

从评论中的代码进行编辑

我不能说没有logcat的确切错误,但我看到的第一个问题是在context中初始化AsyncTask时。您不希望使用getApplicationContext(),尤其不是您的使用方式。我想你得到NPE,因为context尚未初始化。您正在构造函数中传递Context,因此您只需执行

this.context = context

但是,您的AsyncTask似乎是RegisterActivity的内部类,这意味着它可以访问RegisterActivity及其Context的所有成员变量。这意味着,要启动Activity,您可以使用RegisterActivity.this代替context

    @Override
    protected void onPostExecute(String result)
    {                     
          super.onPostExecute(result);                       
          //if (result == "Successful registration!")                    
          //String i;
          //i = "da";
          context.startActivity(new Intent(RegisterActivity.this,LoginActivity.class));  // change this here

如上所述,context如果它是一个内部类,则不需要你的构造函数,但如果它是一个单独的文件,它就像

class RegisterTask extends AsyncTask<String, Void, String>{

            Context context;
            private RegisterTask(Context context){
                    this.context = context;  // use the variable (context) passed in the constructor above

答案 1 :(得分:0)

这是解决我的问题的代码(感谢CodeMagic - 我不确定这是否是最好的方法): 内班:

class RegisterTask extends AsyncTask<String, Void, String>{


    @Override
    protected String doInBackground(String... params) {
        String message = null;
        EditText username = (EditText) findViewById( R.id.register_username_text );
        EditText password = (EditText) findViewById( R.id.register_password_text );
        EditText passwordrtp = (EditText) findViewById( R.id.register_repeatpassword_text );
        EditText email = (EditText) findViewById( R.id.register_email_text );
        EditText firstname = (EditText) findViewById( R.id.register_firstname_text );
        EditText lastname = (EditText) findViewById( R.id.register_lastname_text );
        final String user = username.getText().toString();
        final String pass = password.getText().toString();
        final String passrtp = passwordrtp.getText().toString();
        final String mail = email.getText().toString();
        final String fname = firstname.getText().toString();
        final String lname = lastname.getText().toString();

        guiProgressDialog(true);
        if(user.length() < 4) guiNotifyUser("Username must have at least 4 characters!");
        else if(pass.length() < 4) guiNotifyUser("Password must have at least 4 characters!");
        else if(!pass.equals(passrtp)) guiNotifyUser("Password is not same in both fields!");
        else if(!isValidEmail(mail)) guiNotifyUser("Your email is not valid email address!");
        else if(fname.equals("") || lname.equals("")) guiNotifyUser("All fields are mandatory!");
        else {
            try {
                message = AutoDiaryHttpHelper.signUp(user, md5(pass), mail, fname, lname);
                guiNotifyUser(message);//prosla vodi na sledeci activity "Succesfull registration"

            }
            catch(Exception e) {
                e.printStackTrace();
            }
        }
        guiProgressDialog(false);



        return message;
    }

    @Override
    protected void onPostExecute(String result)
    {
        super.onPostExecute(result);

        if (result.equalsIgnoreCase("Successful registration!"))
        {

            RegisterActivity.this.startActivity(new Intent(context,LoginActivity.class));
            RegisterActivity.this.finish();
        }


    }
}

并从按钮监听器调用:

public void onClick(View v) {

    switch(v.getId())
    {
    case R.id.register_register_button:

        RegisterTask registerTask = new RegisterTask();
        registerTask.execute();

        break;