IntentService的onPostExecute类似吗?

时间:2014-11-22 06:12:20

标签: android android-asynctask intentservice

我试图从活动中的AsyncTask迁移到IntentService。我的主要目标是尽可能多地保留活动,以便可以从应用程序中的不同位置轻松触发服务,而无需依赖活动来处理结果。

在AsyncTask中,我使用onPostExecute来处理完所有繁重工作后的结果,但这似乎并不存在于IntentService中。我讨厌使用ResultReceiver的想法,因为我必须包含结果数据,强制主线程然后处理反序列化它。除了转身并让ResultReceiver使用AsyncTask对结果进行反序列化之外,还有其他的替代方法吗?

谢谢!

更新

我无法想出更好的东西,所以我最终使用了ResultReceiver。我的服务将原始数据(字符串)返回给接收者,接收者然后解析字符串并创建Java对象。我的接收器使用强类型对象回调我的活动。它工作得很好,但是使用服务,接收器和内部接收器回调类肯定会很笨拙。

3 个答案:

答案 0 :(得分:0)

在Asynctask中,onPostExecute在UI线程上运行。因此,如果您打算在UI线程上完成主要工作,则在onPostExecute上处理结果不会有帮助。 在你的情况下,你可以像后台线程本身中的反序列化那样进行繁重的工作。 如果是webservice调用,请在同一服务线程中执行服务调用和结果处理。

答案 1 :(得分:0)

您可以使用绑定到主线程的Handler来自行实现此功能。一个Handler is 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 (varmarken@gmail.com).
 */
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);
    }
}

答案 2 :(得分:0)

您始终可以在onHandleIntent中广播意图,并在BroadcastReceiver中接收该意图。来自OnReceive的{​​{1}}在主线程上被调用。

相关问题