2014-11-22 46 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在主线程中调用。