从服务开始活动并等待结果 [英] Starting an activity from a service and wait for the result

查看:135
本文介绍了从服务开始活动并等待结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面临着以下问题:我需要从服务开始的活动。这是非常重要的服务等待来自活动结果的之前继续下一个方法。

I am facing the following problem: I need to start an activity from a service. It is very important that the service waits for a result from the activity before continuing to the next method.

目前我有这样的事情:

startActivity(new Intent(this, GoogleAuthHelperActivity.class), FLAG_ACTIVITY_NEW_TASK);
//code should wait for the result of the GoogleAuthHelperActivity before continuing
GoogleAuthHelperActivity.apiClient.isConnected();//gives nullpointer

我有认证到Dropbox的API同样的问题,所以我需要一个通用的解决方案。

I have the same problem with authenticating to the Dropbox API, so I need a generic solution.

任何想法如何解决这个问题?

Any ideas how to solve this?

推荐答案

有没有等同于 startActivityForResult 的服务,所以你必须推出自己的。

There is no equivalent to startActivityForResult in Service, so you have to roll your own.

第一种选择:

您可以使用多个标准的Java工具,对于这一点,如对象.wait / Object.notify ,需要一个共享对象的引用。

You can use several standard Java tools for this, like Object.wait / Object.notify, that require a shared object reference.

例如,某处声明:

public static final Object sharedLock = new Object();

和您的服务中做到:

startActivity(new Intent(this, GoogleAuthHelperActivity.class), FLAG_ACTIVITY_NEW_TASK);
synchronized (sharedLock) {
    sharedLock.wait();
}

和在活动:

// do something upon request and when finished:
synchronized (sharedLock) {
    sharedLock.notify();
}

有在 java的其它更复杂的类此。 util.concurrent程序包,您可以使用此。不过要小心,那服务同一个线程活动上运行,因此如果你不开始从服务一个新的线程,那么这将无法工作

There are other more sophisticated classes for this in the java.util.concurrent package that you can use for this. Be careful though, that Services run on the same thread as the Activity, so if you are not starting a new Thread from the Service, then this will not work.

另一个可能的问题是,如果你不能分享它们两者之间的对象引用(因为它们在不同的进程中运行)。然后,你必须预示着一些其他的方式整理。

Another possible problem is if you cannot share an object reference between them two (because they run in different processes). Then you have to signal the finishing in some other way.

第二个选项:

您可以在两个部分(前和活动后)划分服务code。运行活动,并发送一个新的意图的服务,当你完成。在收到本次服务的,你继续第二部分。

You could split your Service code in two parts (before and after the activity). Run the activity and send a new intent to the Service when you are done. Upon receipt of this second Service, you continue with the second part.

这篇关于从服务开始活动并等待结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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