2013-04-19 61 views
0

我有一個只包含各種數據庫查詢的靜態函數的類。由於它們都與網絡相關,所以我需要在另一個線程中執行該代碼。我正試圖找到實現這一點的最佳方式。Android網絡與線程

public class MyClass { 

    public static void someFunction() { 
     ... 
    } 

    public static void anotherFunction() { 
     ... 
    } 

} 

我想這樣做是這樣的:

public class MyClass { 

    public static void someFunction() { 
     new AsyncTask<Void, Void, Void>() { 
      @Override 
      protected Void doInBackground(Void... params) { 
       ... 
      } 
     } 
    } 

    public static void anotherFunction() { 
     new AsyncTask<Void, Void, Void>() { 
      @Override 
      protected Void doInBackground(Void... params) { 
       ... 
      } 
     } 
    } 

} 

或創建一個新的線程,當我把這些功能:

new AsyncTask<Void, Void, Void>() { 
    @Override 
    protected Void doInBackground(Void... params) { 
     MyClass.someFunction(); 
    } 
} 

new AsyncTask<Void, Void, Void>() { 
    @Override 
    protected Void doInBackground(Void... params) { 
     MyClass.anotherFunction(); 
    } 
} 

最後,我想知道是否有一種方法運行與主線程並行的單個線程,該主線程將專門處理這些函數調用。主線程會調用這些函數,另一個線程會運行它們。

有沒有人有任何想法來實現這個最好的方式?謝謝!

+0

可能你應該使用內部類來完成異步任務。只是閱讀更多的API ..它有一個例子。當然,你可以定製它。 http://developer.android.com/reference/android/os/AsyncTask.html – xiriusly

回答

0

標準Java併發實用程序最適合這種情況。

例如:

private static final ExecutorService exe = Executors.newSingleThreadExecutor(); 
... 
exe.execute(new Runnable() { 
    public void run() { 
     ... 
     someFunction(); 
     ... 
    } 
}); 
0

閱讀ExecutorServiceExecutorService允許您按照您的要求管理線程。如果你想讓你的線程按順序產生,你可以簡單地使用ExecutorService ex = Executors.newSingleThreadExecutor(),並隨後將你所有的線程添加到這個executorService中。

ex.submit(runnableInstance)

不過,我也一直在你所面臨的相同問題。我也使用線程從數據庫中進行查詢。但是,它使我的代碼看起來很亂。如果涉及簡單的操作,我建議你在主線程中使用查詢。它幾乎不會給應用程序的響應帶來任何滯後。這樣,你的代碼將會非常可管理。

編輯:

很久以前,我也讀到CursorLoader類,允許你在後臺運行您的查詢,並可以通過實施LoaderManager.LoaderCallbacks<Cursor>使用。通過這種方式,您不必編寫難看的代碼來在後臺執行每個查詢。但是,要使用此功能,您需要將數據庫封裝在ContentProvider中。

0

我相信你最簡單的解決辦法是使用IntentService

摘自Android的文檔

All requests are handled on a single worker thread -- they may take as long as necessary (and will not block the application's main loop), but only one request will be processed at a time. 

你只需要處理onHandleIntent

它做大量的工作,你和它是服務的一個子類,可以直接綁定到服務或其他方式(Intent..etc)來獲取數據。