Java的FutureTask可以替代AsyncTask吗?

时间:2016-05-26 02:36:43

标签: android multithreading android-asynctask futuretask

文档说AsyncTask旨在处理短操作(最多几秒),并声明像FutureTask这样的Java类对于持续时间较长的操作更好。所以我尝试使用FutureTask将我的位置更新发送到服务器,但我收到了NetworkOnMainThreadException。我不想使用AsyncTask,因为我想保持http连接打开,直到更新被取消。这是我的代码:

SendLocation updates = new SendLocation(idt, String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()));

                            FutureTask ft = new FutureTask<String>(updates);
                            boolean b = ft.cancel(false);
                            ft.run();

class SendLocation implements Callable<String> {
        String t, la, lo;
        public SendLocation(String a, String b, String c){
            this.t = a;
            this.la = b;
            this.lo = c;
        }
        public String call() {
            sendUpdates(token, la, lo);
            return "Task Done";
        }

        public void sendUpdates(String a, String b, String c){
            HttpURLConnection urlConn = null;
            try {
                    try {
                        URL url;
                        //HttpURLConnection urlConn;
                        url = new URL(remote + "driver.php");
                        urlConn = (HttpURLConnection) url.openConnection();
                        System.setProperty("http.keepAlive", "true");
                        //urlConn.setDoInput(true); //this is for get request
                        urlConn.setDoOutput(true);
                        urlConn.setUseCaches(false);
                        urlConn.setRequestProperty("Content-Type", "application/json");
                        urlConn.setRequestProperty("Accept", "application/json");
                        urlConn.setRequestMethod("POST");
                        urlConn.connect();
                        try {
                            //Create JSONObject here
                            JSONObject json = new JSONObject();
                            json.put("drt", a);
                            json.put("drlat", b);
                            json.put("drlon", c);
                            String postData = json.toString();

                            // Send POST output.
                            OutputStreamWriter os = new OutputStreamWriter(urlConn.getOutputStream(), "UTF-8");
                            os.write(postData);
                            Log.i("NOTIFICATION", "Data Sent");

                                os.flush();
                                os.close();

                            BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
                            String msg = "";
                            String line = "";
                            while ((line = reader.readLine()) != null) {
                                msg += line;
                            }
                            Log.i("msg=", "" + msg);

                        } catch (JSONException jsonex) {
                            jsonex.printStackTrace();
                            Log.e("jsnExce", jsonex.toString());
                        }
                    } catch (MalformedURLException muex) {
                        // TODO Auto-generated catch block
                        muex.printStackTrace();
                    } catch (IOException ioex) {
                        ioex.printStackTrace();
                        try { //if there is IOException clean the connection and clear it for reuse(works if the stream is not too long)
                            int respCode = urlConn.getResponseCode();
                            InputStream es = urlConn.getErrorStream();
                            byte[] buffer =  null;
                            int ret = 0;
                            // read the response body
                            while ((ret = es.read(buffer)) > 0) {
                                Log.e("streamingError", String.valueOf(respCode) +  String.valueOf(ret));
                            }
                            // close the errorstream
                            es.close();
                        } catch(IOException ex) {
                            // deal with the exception
                            ex.printStackTrace();
                        }
                    }
            } catch (Exception e) {
                e.printStackTrace();
                Log.e("ERROR", "There is error in this code " + String.valueOf(e));
            }
        }
    } 

它是否在工作线程中执行?如果答案是否定的,为什么docs say that it is an alternative to AsyncTask

1 个答案:

答案 0 :(得分:0)

您的代码不得位于void run()方法中。这是运行异步代码的地方。