Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 平台調用 Web Service:用 Callable 與 Future 獲取線程返回值

編輯:關於 Android 程式設計

接上文。

前文中提到的遺留問題

以前我對 Java 多線程的理解僅停留在實現 Runnable 接口或繼承 Thread 類、重寫 run() 方法、最後 start() 就算完事。但一旦涉及死鎖、對共享資源的訪問、隨時監控線程狀態與執行順序,以及獲取線程返回值等場景,就顯得力不從心了。

Callable 與 Future 簡介

Callable 接口代表一段可以調用並返回結果的代碼;Future 接口則表示異步任務執行時的狀態、返回值等信息。所以說,Callable 用於產生結果,Future 用於獲取結果。

1. Callable

Callable 是一個接口,只包含一個 call() 方法,它是一個返回結果並可能拋出異常的任務。為便於理解,可以把 Callable 類比為 Runnable,而 call() 方法則類似於 run() 方法。源碼如下:

public interface Callable {
    V call() throws Exception;
}

2. Future

Future 也是一個接口,用於表示異步計算的結果,提供了檢查計算是否完成、等待完成並獲取結果的方法。源碼如下:

public interface Future {
    boolean cancel(boolean mayInterruptIfRunning); // 嘗試取消任務
    boolean isCancelled();                          // 是否已被取消
    boolean isDone();                               // 是否已完成
    V get() throws InterruptedException, ExecutionException;               // 獲取結果
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;   // 超時獲取結果
}

Callable 和 Future 的基本用法

import java.util.concurrent.*;

class MyCallable implements Callable {
    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 0; i < 100; i++) sum += i;
        return Integer.valueOf(sum);
    }
}

public class CallableTest1 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService pool = Executors.newSingleThreadExecutor(); // 創建線程池
        Callable c1 = new MyCallable();                             // 創建有返回值的任務
        Future f1 = pool.submit(c1);                                // 提交任務並獲取 Future
        System.out.println(f1.get());                               // 輸出結果
        pool.shutdown();                                            // 關閉線程池
    }
}

運行結果為 4950。

結果說明:在主線程 main 中,先通過 newSingleThreadExecutor() 新建線程池,接著創建 Callable 對象 c1,再通過 pool.submit(c1) 把它提交到線程池處理,並將返回結果保存到 Future 對象 f1 中;然後用 f1.get() 獲取結果,最後通過 pool.shutdown() 關閉線程池。

回到主題:調用查詢手機號歸屬地的 WebService

通過上面這個簡單的例子,我們完全可以把原本用 Runnable 或 Thread 實現的線程,改寫成 Callable 和 Future 的形式:

public class MainActivity extends Activity {
    public static final String TAG = "webService_pj";
    private EditText phoneSecEditText;
    private TextView resultView;
    private Button queryButton;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        phoneSecEditText = (EditText) findViewById(R.id.phone_sec);
        resultView = (TextView) findViewById(R.id.result_text);
        queryButton = (Button) findViewById(R.id.query_btn);
        queryButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String phoneSec = phoneSecEditText.getText().toString().trim();
                if ("".equals(phoneSec) || phoneSec.length() < 7) {
                    phoneSecEditText.setError("您輸入的手機號碼(段)有誤!");
                    phoneSecEditText.requestFocus();
                    resultView.setText("");
                    return;
                }
                String nameSpace = "https://WebXml.com.cn/";
                String methodName = "getMobileCodeInfo";
                String endPoint = "https://webservice.webxml.com.cn/WebServices/MobileCodeWS.asmx";
                String soapAction = "https://WebXml.com.cn/getMobileCodeInfo";
                ArrayList params = new ArrayList();
                ArrayList vals = new ArrayList();
                params.add("mobileCode");
                params.add("userId");
                vals.add(phoneSec);
                vals.add("");

                // 通過 Callable 和 Future 創建線程調用 WebService
                CallableThread callable = new CallableThread(
                        nameSpace, methodName, endPoint, soapAction, params, vals);
                ExecutorService executor = Executors.newCachedThreadPool();
                Future future = executor.submit(callable);
                try {
                    resultView.setText(future.get());
                    executor.shutdown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private class CallableThread implements Callable {
        private String nameSpace, methodName, endPoint, soapAction;
        private ArrayList params;
        private ArrayList vals;
        public CallableThread(String nameSpace, String methodName, String endPoint,
                              String soapAction, ArrayList params, ArrayList vals) {
            this.nameSpace = nameSpace;
            this.methodName = methodName;
            this.endPoint = endPoint;
            this.soapAction = soapAction;
            this.params = params;
            this.vals = vals;
        }
        @Override
        public String call() throws Exception {
            // 具體的網絡請求實現見上篇文章或源碼
            return getRemoteInfo(nameSpace, methodName, endPoint, soapAction, params, vals);
        }
    }
}

至此,在 Android 上調用 WebService 並獲取線程返回值的功能就完整實現了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved