在Android的IntentService等待异步回调 [英] Waiting for asynchronous callback in Android's IntentService

查看:992
本文介绍了在Android的IntentService等待异步回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 IntentService 启动异步任务的另一个类,应该再等待结果。

I have an IntentService that starts an asynchronous task in another class and should then be waiting for the result.

的问题是, IntentService 将尽快完成的 onHandleIntent(...)方法结束运行,对吧?

The problem is that the IntentService will finish as soon as the onHandleIntent(...) method has finished running, right?

这意味着,通常情况下, IntentService 将立即启动异步任务后关闭,将不存在了接收效果。

That means, normally, the IntentService will immediately shut down after starting the asynchronous task and will not be there anymore to receive the results.

public class MyIntentService extends IntentService implements MyCallback {

    public MyIntentService() {
        super("MyIntentService");
    }

    @Override
    protected final void onHandleIntent(Intent intent) {
        MyOtherClass.runAsynchronousTask(this);
    }

}

public interface MyCallback {

    public void onReceiveResults(Object object);

}

public class MyOtherClass {

    public void runAsynchronousTask(MyCallback callback) {
        new Thread() {
            public void run() {
                // do some long-running work
                callback.onReceiveResults(...);
            }
        }.start();
    }

}

我怎样才能使上述工作的片段?我已经试图把视频下载(15000)(任意时间)在 onHandleIntent(...)之后在启动任务。 Itseems工作

How can I make the snippet above work? I've already tried putting Thread.sleep(15000) (arbitrary duration) in onHandleIntent(...) after starting the task. Itseems to work.

但它肯定似乎并不干净的解决方案。也许甚至有一些严重的问题这一点。

But it definitely doesn't seem to be clean solution. Maybe there are even some serious problems with that.

任何更好的解决办法吗?

Any better solution?

推荐答案

使用标准的服务类,而不是 IntentService ,从 onStartCommand()回调启动异步任务,并摧毁了服务当您收到完成回调。

Use the standard Service class instead of IntentService, start your asynchronous task from the onStartCommand() callback, and destroy the Service when you receive the completion callback.

与该问题会正确处理服务的破坏的同时运行任务的服务的结果的情况下正在重新启动,而它已经在运行。如果您需要处理这种情况,那么你可能需要建立一个运行的计数器或一组回调,并摧毁了服务时,才全部完成。

The issue with that would be to correctly handle the destruction of the Service in the case of concurrently running tasks as a result of the Service being started again while it was already running. If you need to handle this case, then you might need to set up a running counter or a set of callbacks, and destroy the Service only when they are all completed.

这篇关于在Android的IntentService等待异步回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆