【问题标题】:Android thread finished callbackAndroid线程完成回调
【发布时间】:2015-04-06 04:50:59
【问题描述】:

我想在收到服务器响应后执行 http post。 如果服务器响应为假,则 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 条件不起作用?

【问题讨论】:

  • 是否有任何错误?这个isAvailable.equals("false") 的价值是什么
  • 但是 isAvailable 的值为 false。

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


【解决方案1】:

如果服务器响应为假,http post 将执行,否则不执行 执行。我该怎么做呢

由于您在 checkUseraddUser 中使用线程而出现问题。线程的执行不停止当前线程的执行。

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

addUser 方法也是如此。

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

【讨论】:

  • 谢谢你的帮助,我会改变它。
  • @nmkkannan:好吧,你自己做,我一定会尽力帮助你
  • @nmkkannan:什么问题?
【解决方案2】:

您正在使用新线程在这里执行 http 请求。因此,您的委托方法不同步。 addUsercheckUser 将在您的 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(){ 代码都应以对侦听器的所有调用结束。

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

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

【讨论】:

    猜你喜欢
    • 2018-02-15
    • 1970-01-01
    • 2016-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-07
    相关资源
    最近更新 更多