2014-11-22 99 views
2

我想從活動中的AsyncTask移動到IntentService。我的主要目標是保持儘可能多的活動,以便在不依賴活動來處理結果的情況下輕鬆地從應用程序中的不同位置觸發服務。與onPostExecute for InServiceService類似嗎?

在一個AsyncTask中,我會使用onPostExecute在完成所有繁重工作後處理結果,但對於IntentService來說似乎並不存在。我討厭使用ResultReceiver的想法,因爲我必須分析結果數據,強制主線程處理反序列化。有沒有其他的選擇我失蹤了,然後轉身,讓ResultReceiver使用AsyncTask來反序列化結果?

謝謝!

更新

我不能想出什麼好,所以我結束了使用ResultReceiver。我的服務將原始數據(字符串)返回給接收方,然後接收方解析字符串並創建Java對象。我的接收器使用強類型對象回調我的活動。它工作得很好,但它肯定感覺笨拙,不得不使用服務,接收器和內部接收器回調類。

+0

您可以從onstart方法調用asycntask – koutuk 2014-11-22 06:22:32

回答

0

在Asynctask中,onPostExecute在UI線程上運行。因此,如果你的意圖是從UI線程完成主要工作,那麼在onPostExecute上處理結果將無濟於事。 在你的情況下,你可以像後臺線程本身那樣進行反序列化。 如果它是web服務調用,請在同一個服務線程中執行服務調用和結果處理。

+0

但是使用AsyncTask,您可以將常規數據傳回onPostExecute。我對IntentService的印象是,你必須在一個Bundle上放置Parcelable數據,這樣就迫使Handler把這些數據轉換成它的最終形式。我想知道是否有我丟失的東西,或者如果我只是需要轉向,並在ResultReceiver中使用AsyncTask的doInBackground來解析數據(因爲我不希望它在主線程上運行)。我是希望在IntentActivity中做所有事情,但看起來我必須將它與ResultReceiver分離。希望這能夠澄清我的問題。 – Dennis 2014-11-22 06:51:56

0

你可以使用綁定到主線程的Handler來實現這個。 A Handleris tied to the thread that creates it。因此,通過在由主線程調用的代碼塊中創建Handler,例如作爲onCreate()的一部分,您可以在主線程作業列表中掛鉤。現在,在onHandleIntent(Intent intent)實現的最後,您只需將要在主線程上運行的語句集發佈到Handler實例。

示例代碼:

import android.app.IntentService; 
import android.content.Intent; 
import android.os.Handler; 
import android.widget.Toast; 

/** 
* @author Janus Varmarken ([email protected]). 
*/ 
public class ExampleIntentService extends IntentService { 

    // Handler tied to the main thread. 
    private Handler mHandler; 

    public ExampleIntentService() { 
     super(ExampleIntentService.class.getSimpleName()); 
    } 

    @Override 
    public void onCreate() { 
     // Make sure to call super such that IntentService can properly manage its lifecycle 
     // (it needs to create a background thread and manage a job list for this thread) 
     super.onCreate(); 

     // As onCreate is run on the main thread, we can tie a Handler to the main thread by 
     // creating it here. 
     mHandler = new Handler(); 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) { 
     // Do heavy lifting here... 
     // Here we just sleep for the sake of the example. 
     try { 
      Thread.sleep(5000); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 

     // When heavy lifting is done: 
     // Create a runnable containing the statements you want to run on the main/UI thread. 
     Runnable uithreadStatements = new Runnable() { 
      @Override 
      public void run() { 
       // main/UI thread statements goes here. 
       Toast.makeText(ExampleIntentService.this, "Toasting on main thread.", Toast.LENGTH_SHORT).show(); 
      } 
     }; 

     // Post the job to the handler instance which is tied to the main thread 
     // so that the job will be executed on the main/UI thread. 
     mHandler.post(uithreadStatements); 
    } 
} 
0

您可以隨時在onHandleIntent廣播意圖和BroadcastReceiver接受它。 OnReceive from BroadcastReceiver在主線程中調用。