简体   繁体   English

在android主线程和另一个线程之间同步

[英]synchronized between the main thread of android and another thread

Android by design doesn't allow network on the main thread it can be forced but its not a good practice. 根据设计,Android不允许在主线程上进行网络连接,但可以强制这样做,但这不是一个好习惯。 So I want to synchronized the main thread and one other thread so I can get the response from the database for user authentication. 因此,我想同步主线程和另一个线程,以便可以从数据库获取响应以进行用户身份验证。 My synchronization is not working.. 我的同步无法正常工作..

This is the code in the main thread.. 这是主线程中的代码。

if (loginBTN.getId() == ((Button) v).getId()) {

    String emailId = loginField.getText().toString().trim();
    String password = passwordField.getText().toString().trim();

    postParameters.add(new BasicNameValuePair("username", emailId));
    postParameters.add(new BasicNameValuePair("password", password));

    try {

        System.out.println("b4 response" + responseToString);

        checkLogin();

        System.out.println("after response" + responseToString);

        synchronized (this) {

            while (isAvailable == false) {

                wait();

            }

            if (responseToString.equalsIgnoreCase("1")) {

                statusLBL.setText("Login Successful...");

            }

            else {

                statusLBL.setText("Sorry Incorrect Username or Password...");

            }
        }

    }

    catch (Exception e) {

        statusLBL.setText(e.toString());
    }

}




private void checkLogin() {

        Thread thread = new Thread(new Runnable() {

            @Override
            public void run() {

                try {

                    HttpClient http = new DefaultHttpClient();
                    HttpPost request = new HttpPost("http://example.org/api/android_gradhub/login_user.php");
                    UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
                    request.setEntity(formEntity);
                    HttpResponse response = http.execute(request);
                    HttpEntity entity = response.getEntity();

                    // responseToString = EntityUtils.toString(entity);

                    synchronized (this) {

                        while (isAvailable == true) {

                            wait();

                        }

                        responseToString = EntityUtils.toString(entity);
                        notifyAll();
                    }

                    System.out.println("response " + responseToString);
                }

                catch (Exception e) {

                    e.printStackTrace();
                }
            }
        });

        thread.start();

    }

Remove all of your synhronization and then just put thread.join() as the last statement in checkLogin . 删除所有synhronization,然后只是把thread.join()中的最后一条语句checkLogin This is the simplest way to wait for the thread to complete before proceeding. 这是在继续操作之前等待线程完成的最简单方法。

If you want to decide when to wait (like you might want to do other stuff in the main program before the login needs to be checked) then you can return the thread from checkLogin . 如果您想决定何时等待(例如您可能想要在需要检查登录名之前在主程序中做其他事情),则可以从checkLogin 返回线程 Than you decide when to join back in your main program. 然后,您决定何时重新join主程序。 (ie signature changes to public Thread checkLogin and last line of checkLogin becomes return thread . Back in your main program, call Thread thread = checkLogin(); when you want to wait for the checkLogin to finish - use thread.join() , up until that point Main thread and checkLogin thread is concurrent). (即签名更改为public Thread checkLoginpublic Thread checkLogin最后一行成为return thread 。回到主程序中,调用Thread thread = checkLogin();当您要等待checkLogin完成时-使用thread.join() ,向上直到那一点主线程和checkLogin线程是并发的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM