从setOnClickListener中执行时,AsyncTask无法正常工作

时间:2013-02-16 17:03:49

标签: android android-asynctask

我正在尝试登录到Web服务器并且我正确运行了代码但是当我尝试在页面周围构建日志时,事情开始出错了。

我正在使用Eclipse Android工具中提供的示例登录页面,如果有人想看到任何额外的代码。

如果我从OnClickHandler中执行,那么DefaultHttpClient似乎超时了。它不会返回任何内容,或者它是否会返回“无对等证书”,我知道这是错误的。

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

......设置内容

    mAuthTask = new UserLoginTask();
    findViewById(R.id.sign_in_button).setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(attemptLogin()){
                        mAuthTask.execute();
                    }
                }
            });
    //mAuthTask = new UserLoginTask(); 
    //mAuthTask.execute();  // Works if called from here.

这是相关的AsyncTask代码:

public class UserLoginTask extends AsyncTask<String, Void, String> {

    @Override
    protected void onPreExecute() {
        Log.i(TAG,"Thread name (from preexecute) : " +  Thread.currentThread().getName());
    }

    protected String doInBackground(String... urls) {
        DefaultHttpClient client = AppHttpClient.getClient();
        HttpPost httppost = new HttpPost("https://euw.leagueoflegends.com/user/login");
        String result = "";
        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
            nameValuePairs.add(new BasicNameValuePair("name", "exampleusername"));
            nameValuePairs.add(new BasicNameValuePair("pass", "blahblah"));
            nameValuePairs.add(new BasicNameValuePair("form_id", "user_login"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            Log.i(TAG,"Thread name (passed into doInBackground) : " +  urls[0]);
            Log.i(TAG,"Thread name (from doInBackground) : " +  Thread.currentThread().getName());
            HttpResponse response2 = client.execute(httppost);
            InputStream in = response2.getEntity().getContent();
            //result = readStream(in);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

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

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

1 个答案:

答案 0 :(得分:0)

以下是来自Google工程师的有趣answer

  

在线程上调用AsyncTask的pre和postExecute方法   哪个任务实例是创建的。你调用execute()的地方没有   物。创建任务的线程必须是looper   线程和实践应始终是主线程(或UI)   线程。)

修改

您应该尝试此代码(未经测试):

private mAuthTask = new UserLoginTask();
findViewById(R.id.sign_in_button).setOnClickListener(
        new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(attemptLogin()){
                    Activity.this.runOnUiThread( new Runnable() {
                        @Override
                        public void run() {
                            mAuthTask.execute();
                        }
                    });
                }
            }
        });