Android线程结束回调

Android thread finished callback

我想在收到服务器响应后执行 http post。 如果服务器响应为 false,则 http post 将执行,否则不执行。 我该怎么做。

我的android主要activity代码:

if (Utility.isValidMobile(mobileNumber)) {
            String isAvailable = userDelegate.checkUser(mobileNumber, context);


            if (isAvailable.equals("false")) {
                userDelegate.addUser(userMO, context);
                Toast.makeText(getApplicationContext(), "Your mobile number is" + mobileNumber + "name is" + userName, Toast.LENGTH_LONG).show();
            } else if (isAvailable.equals("true")) {
                Toast.makeText(getApplicationContext(), "Your mobile number is already registerd", Toast.LENGTH_LONG).show();
            }
        } 

当我点击注册按钮时,上面的代码将被执行

我的 Userdelegate class 代码:

public void addUser(final UserMO userMo, final Context context) {

    final String jsonStringObject = gson.toJson(userMo);

    Thread t = new Thread() {
        public void run() {
            Looper.prepare(); // for the child Thread
            HttpClient client = new DefaultHttpClient();
            HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
                                                                                    // Limit
            try {
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("userBO", jsonStringObject));
                HttpPost post = new HttpPost("http://192.168.1.101:8080/warname/user/addUser");
                post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = client.execute(post);
                BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                Toast.makeText(context, "Your user id " + rd.readLine(), Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                e.printStackTrace();
            }
            Looper.loop(); // Loop in the message queue
        }
    };
    t.start();

}

public void getMatchingExistingUserList(final String mobile_number, final Context context) {

    final String jsonStringObject = gson.toJson(mobile_number);

    Thread t = new Thread() {
        public void run() {
            Looper.prepare(); // for the child Thread
            HttpClient client = new DefaultHttpClient();
            HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
                                                                                    // Limit
            try {
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("userBO", jsonStringObject));
                HttpPost post = new HttpPost("http://192.168.1.101:8080/warname/user/addUser");
                post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = client.execute(post);
                BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                final String responseString = rd.readLine();
            } catch (Exception e) {
                e.printStackTrace();
            }
            Looper.loop(); // Loop in the message queue
        }
    };
    t.start();
}

public String checkUser(final String mobile_number, final Context context) {

    final StringBuilder isAvailable = new StringBuilder();

    Thread t = new Thread() {
        @Override   
        public void run() {
            Looper.prepare(); // for the child Thread
            try {
                HttpClient client = new DefaultHttpClient();
                HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("MobileNumber", gson.toJson(mobile_number)));
                HttpPost post = new HttpPost("http://192.168.1.101:8080/warname/user/checkUserMobileNumber");
                post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = client.execute(post);
                BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                isAvailable.append(rd.readLine());
            } catch (Exception e) {
                e.printStackTrace();
            }
            Looper.loop(); // Loop in the message queue
        }
    };
    t.start();
    return isAvailable.toString();
}

问题是我得到的响应是错误的,但 if 条件不起作用。 如何解决这个问题。

更改后:

if (Utility.isValidMobile(mobileNumber)) {
            new AsyncTask<Void, Void, String>() {
                @Override
                protected String doInBackground(Void... arg0) {
                    return userDelegate.checkUser(mobileNumber, context);
                }

                @Override
                protected void onPostExecute(String isAvailable) {
                    Toast.makeText(getApplicationContext(), isAvailable, Toast.LENGTH_LONG).show();
                    if (isAvailable.equals("false")) {
                        Toast.makeText(getApplicationContext(), "Your mobile number is" + mobileNumber + "name is" + userName, Toast.LENGTH_LONG).show();
                        userDelegate.addUser(userMO, context);
                    } else if (isAvailable.equals("true")) {
                        Toast.makeText(getApplicationContext(), "Your mobile number is already registerd", Toast.LENGTH_LONG).show();
                    }
                }
            }.execute(null, null, null);
        }

if 条件不工作?

If server response is false the http post will execute else not execute. How can i do for this

出现问题是因为您在 checkUseraddUser 中使用线程。线程的执行没有停止当前线程的执行。

例如,当从主线程调用checkUser方法时,final StringBuilder isAvailable = new StringBuilder();在主线程上执行,线程t在单独执行。所以系统 return 控制下一行 return isAvailable.toString(); 无需等待 线程执行完成意味着 checkUser 方法总是 return nullempty 字符串。

addUser 方法也是如此。

要根据 checkUser 方法响应的结果执行任务,请使用 AsyncTask class。

您正在使用新线程在此处执行 http 请求。因此,您的委托方法不同步。 addUsercheckUser 将 return 在您的 http 请求完成之前。

要编写像您这样的多线程代码,您可能需要使用某种侦听器来完成线程通信工作。

例如,您可以将侦听器传递给您的委托,如下所示

class Listener{
    private Handler handler = new Handler();
    public void onUserAdded(){
         handler.post(new Runnable(){
               public void run(){
                     // Toast your thing
               }
         });
    }

    public void onUserChecked(final boolean available){
         handler.post(new Runnable(){
               public void run(){
                     if(available){
                           // Toast your thing
                     }else{
                          userDelegate.addUser(userMO, context);
                     }
               }
         });
    }
}

你所有的 new Thread(){ run(){ 代码都应该以对监听器的所有调用结束。

如您所见,我使用处理程序 post 返回 UI 线程。这对您通知 UI 元素您的 none-UI 线程中发生的事情非常重要。

另外,我看不到你用 Looper.prepare()Looper.loop() 做什么。没有子线程。