1

我正在尝试创建一个登录页面以从我学校的网站上提取一些信息(日程安排信息...等)。该代码完美地作为一个java驱动程序工作,但我试图让它在android上工作。朋友告诉我应该使用AsyncTask模式。有人可以告诉我如何使用AsyncTask下面的代码吗?

public class MainActivity extends Activity implements OnClickListener {
    EditText un,pw;
    TextView error;
    Button ok;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        un=(EditText)findViewById(R.id.et_un);
        pw=(EditText)findViewById(R.id.et_pw);

        ok=(Button)findViewById(R.id.btn_login);
        ok.setOnClickListener(this); 
    }

    public void postLoginData() {
        //Create a new HttpClient and Post Header
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost=new HttpPost("url");

        try {
            EditText un=(EditText)findViewById(R.id.et_un);
            String username=un.getText().toString();

            EditText pw=(EditText)findViewById(R.id.et_pw);
            String password=un.getText().toString();

            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

            entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            entity.addPart("userName", new StringBody("username"));
            entity.addPart("password", new StringBody("password"));
            entity.addPart("btnLogin", new StringBody("Login"));
            entity.addPart("__EVENTTARGET", new StringBody(""));

            //Post to login site
            httppost = new HttpPost("https://my.jcsu.edu/ICS");
            httppost.setEntity(entity);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity response_entity = response.getEntity();
            if (response_entity != null) {
                Jsoup.parse(EntityUtils.toString(response_entity));
            }

            HttpGet httpget = new HttpGet("url");
            response = httpclient.execute(httpget);
            response_entity = response.getEntity();


            if (response_entity != null) {
                Document doc = Jsoup.parse(EntityUtils.toString(response_entity));

                // Get the user's name
                Element userWelcome = doc.getElementById("userWelcome");
                System.out.println("Welcome " + userWelcome.getElementsByTag("strong").get(0).html());

                // Get the user's schedule
                System.out.println("\nCourse Schedule:");
                Elements gbody = doc.getElementsByClass("gbody");
                Element tr = gbody.get(4);
                Elements td = tr.getElementsByTag("td");
                for (Element e : td) {
                    if (e.html().contains("<ul>") || e.html().contains("<a"))
                        continue;
                    else

                        System.out.println(e.html());
                }

                // Get user's information
                System.out.println("\nAcademic Information:");
                System.out.println(doc.getElementById("pg7_V_rptPackage_ctl00_lblDivision").html()
                                   .replace("&nbsp;", ""));
                System.out.println("Faculty Advisors: "
                                   + doc.getElementById("pg7_V_rptPackage_ctl00_rptAdvisor_ctl00_lblAdvisorInfo").html() + ", "
                                   + doc.getElementById("pg7_V_rptPackage_ctl00_rptAdvisor_ctl02_lblAdvisorInfo").html());
                System.out.println("Intended Majors: "
                                   + doc.getElementById("pg7_V_rptPackage_ctl00_rptMajor_ctl00_lblMajorInfo").html());

            }
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View view) {
        if(view == ok){
            postLoginData();
        }
    }

}
4

1 回答 1

1

该方法OnClickListener.onClick将从 UI 线程调用,因此您不应从该方法执行任何长时间运行的操作。从内部onClick,您调用postLoginData它发出网络请求。您不应该从 UI 线程中执行此操作。

除非我遗漏了一些东西,否则我实际上没有任何理由使用AsyncTask上面的,你可以简单地使用 newThread来做后台工作。这是因为您的方法postLoginData只是发出请求并将一些内容打印到System.out.

public void postLoginData() {
    new Thread() {
        // ... body of postLoginData()
    }.start();
}

但是,我假设您实际上还有一些不属于您的代码段的代码,或者稍后会添加一些代码。如果该代码将在网络操作完成后更新 UI,您应该考虑使用AsyncTask. 我将尝试使用它来勾勒出一个示例。

您需要从 UI 线程对 UI 进行任何更新,但您不能在 UI 线程上执行长时间运行的操作,例如网络请求。Android 背后的基本思想AsyncTask是在 UI 线程和后台线程上安排工作。这允许您开始下载数据,在下载发生时更新进度条,并在完成时更新 UI。这是如何postLoginData使用实现的基本草图AsyncTask

PostLoginDataTask extends AsyncTask {
    String username, password;

    onPreExecute() { // runs on the UI thread
        EditText un=(EditText)findViewById(R.id.et_un);
        username=un.getText().toString();

        EditText pw=(EditText)findViewById(R.id.et_pw);
        password=un.getText().toString();
    }

    doInBackground() { // runs on a background thread
        //Create a new HttpClient and Post Header
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost=new HttpPost("url");

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        entity.addPart("userName", new StringBody("username"));
        entity.addPart("password", new StringBody("password"));
        entity.addPart("btnLogin", new StringBody("Login"));
        entity.addPart("__EVENTTARGET", new StringBody(""));

        //Post to login site
        httppost = new HttpPost("https://my.jcsu.edu/ICS");
        httppost.setEntity(entity);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity response_entity = response.getEntity();
        if (response_entity != null) {
            Jsoup.parse(EntityUtils.toString(response_entity));
        }

        HttpGet httpget = new HttpGet("url");
        response = httpclient.execute(httpget);
        response_entity = response.getEntity();

        return response_entity;
    }

    onPostExecute() { // runs on the UI thread
        if (response_entity != null) {
            Document doc = Jsoup.parse(EntityUtils.toString(response_entity));

            // Get the user's name
            Element userWelcome = doc.getElementById("userWelcome");
            System.out.println("Welcome " + userWelcome.getElementsByTag("strong").get(0).html());

            // Get the user's schedule
            System.out.println("\nCourse Schedule:");
            Elements gbody = doc.getElementsByClass("gbody");
            Element tr = gbody.get(4);
            Elements td = tr.getElementsByTag("td");
            for (Element e : td) {
                if (e.html().contains("<ul>") || e.html().contains("<a"))
                    continue;
                else

                    System.out.println(e.html());
            }

            // Get user's information
            System.out.println("\nAcademic Information:");
            System.out.println(doc.getElementById("pg7_V_rptPackage_ctl00_lblDivision").html()
                               .replace("&nbsp;", ""));
            System.out.println("Faculty Advisors: "
                               + doc.getElementById("pg7_V_rptPackage_ctl00_rptAdvisor_ctl00_lblAdvisorInfo").html() + ", "
                               + doc.getElementById("pg7_V_rptPackage_ctl00_rptAdvisor_ctl02_lblAdvisorInfo").html());
            System.out.println("Intended Majors: "
                               + doc.getElementById("pg7_V_rptPackage_ctl00_rptMajor_ctl00_lblMajorInfo").html());

            // Any updates to the UI should go in this method
        }
    }
}

请注意,这并不完全正确并且不会编译。您需要阅读泛型类型参数 Params、Progress 和 Result,并弄清楚如何将其融入您的代码。我把它作为练习留给读者:P 这不是太难,但如果你感到困惑,请随时在评论中提问......

希望有帮助!

于 2012-09-23T22:25:28.280 回答