【问题标题】:Java get result from Thread and RunnableJava 从 Thread 和 Runnable 获取结果
【发布时间】:2014-10-04 12:45:49
【问题描述】:

在下面的代码中,我无法从 getValue 类中获得结果,这就是返回 null 但这必须是返回值。结果是正确的,此函数无法返回。例如这是我的课:

public class JsonService {
    private JSONObject json = new JSONObject();
    public JsonService(final String username, final String password) throws Exception{
        json.put("username", username);
        json.put("password", password);
    }
    public class Foo implements Runnable {
        private String result;

        @Override
        public void run() {
            HttpClient client = new DefaultHttpClient();
            HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
            HttpResponse response;

            try {
                HttpPost post = new HttpPost("http://www.example.com/json_android.php");
                StringEntity se = new StringEntity( json.toString());
                se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                post.setEntity(se);
                response = client.execute(post);
                if(response!=null){
                    InputStream stream = response.getEntity().getContent();
                    result = convertToString(stream);

                    /*
                         I can Log result with below line
                    */
                    Log.e("response is: ", result);

                    /*
                         result is {"username = ":"Hello"}
                    */
                }
            } catch(Exception e) {
                e.printStackTrace();
                Log.e("Error", String.valueOf(e));
            }
        }

        public String getValue() {
            /*
                 return in this fucntion not working
            */
            return result;
        }
    }
    public String request() throws ExecutionException, InterruptedException {
        Foo foo = new Foo();
        new Thread(foo).start();
        return foo.getValue();
    }

如何从Foo 正确获取结果并从reauest() 返回?请帮我。谢谢

【问题讨论】:

    标签: java android android-handler


    【解决方案1】:

    使用FutureTask 并实现Callable

    public class Foo implements Callable<String> {
    
        @Override
        public String call() {
            String result = null;
            HttpClient client = new DefaultHttpClient();
            HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
            HttpResponse response;
    
            try {
                HttpPost post = new HttpPost("http://www.example.com/json_android.php");
                StringEntity se = new StringEntity( json.toString());
                se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                post.setEntity(se);
                response = client.execute(post);
                if(response!=null){
                    InputStream stream = response.getEntity().getContent();
                    result = convertToString(stream);
    
                    /*
                         I can Log result with below line
                    */
                    Log.e("response is: ", result);
    
                    /*
                         result is {"username = ":"Hello"}
                    */
                }
    
            } catch(Exception e) {
                e.printStackTrace();
                Log.e("Error", String.valueOf(e));
            }
            return result;
        }
    }
    

    而不是将其与 FutureTask 一起使用

    public String request() throws ExecutionException, InterruptedException {
       Foo foo = new Foo();
       FutureTask<String> fooFuture = new FutureTask<String>(foo);
       new Thread(fooFuture).start();
       return fooFuture.get();
    }
    

    【讨论】:

    • 如果计算需要很长时间不要ANR吗?因为fooFuture.get(); 阻塞直到结果准备好!
    【解决方案2】:

    getFutureTask 的方法(在上面的答案 return fooFuture.get();)是一个阻塞函数,这意味着当您从 UI 线程调用它时,它会阻塞 UI 线程,因此您的应用会向您发送 ANR错误。我的建议是使用LocalBroadCastManager 来解决它,当计算完成时,它会发送一个本地broadcast,在您的UI 中,您将从嵌入在意图中的Extra 获得onReceive 的结果。 另一种解决方案是使用ruOnUiThread 或从 UI 线程传递处理程序。最后一个是使用post 小部件方法。

    【讨论】:

      猜你喜欢
      • 2015-07-29
      • 1970-01-01
      • 1970-01-01
      • 2023-02-02
      • 1970-01-01
      • 2013-07-02
      • 1970-01-01
      • 1970-01-01
      • 2012-09-24
      相关资源
      最近更新 更多