Android线程完成回调

时间:2015-02-06 05:24:59

标签: android performance android-intent android-activity android-asynctask

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

我的android主要活动代码:

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类代码:

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条件不起作用?

2 个答案:

答案 0 :(得分:2)

您正在使用新线程在此处执行http请求。因此,您的委托方法不同步。 <{1}}和addUser将在您的http请求完成之前返回。

要编写像您这样的多线程代码,您可能希望使用某种类型的侦听器来执行线程通信工作。

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

checkUser

所有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); } } }); } } 代码都应该以对侦听器的所有调用结束。

如您所见,我使用Handler将作品发布回UI线程。这对于通知UI元素非UI线程中发生的事情非常重要。

此外,我无法看到您对new Thread(){ run(){Looper.prepare()所做的工作。没有子线程。

答案 1 :(得分:1)

  

如果服务器响应为false,http post将执行其他操作   执行。我该怎么做呢

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

例如,当从主线程调用checkUser方法时,在主线程上执行的final StringBuilder isAvailable = new StringBuilder();和线程t分别执行。所以系统将控制返回到下一行return isAvailable.toString();而不等待线程执行完成意味着checkUser方法始终返回nullempty字符串。

同样适用于addUser方法。

根据checkUser方法响应的结果使用AsyncTask类执行任务。