Java 来自服务的 StartActivityForResult

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3448485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 00:52:57  来源:igfitidea点击:

StartActivityForResult from a Service

javaandroidbluetooth

提问by

Id like to enable bluetooth like in this example.

我想在这个例子中启用蓝牙。

However my class isnt a Activity but a Service and therefore I can't call startActivityForResult. How can i solve this problem?. I know there are other questions that have been answered like

但是,我的课程不是活动而是服务,因此我无法调用 startActivityForResult。我怎么解决这个问题?。我知道还有其他问题已得到解答,例如

use startActivityForResult from non-activity

使用来自非活动的 startActivityForResult

but this doesn't solve my problem because my application consists of the service and nothing else.

但这并不能解决我的问题,因为我的应用程序由服务组成,仅此而已。

采纳答案by Macarse

Unfortunately you can't do that.

不幸的是,你不能这样做。

The only solution I found (hack) is to first open an Activitywith a Dialog style and then do the call there.

我找到的唯一解决方案(hack)是首先Activity用 Dialog 样式打开一个,然后在那里进行调用。

回答by emote_control

I know this is an older question, but I've run into a similar challenge, and my solution was to create an activity with android:theme="@android:style/Theme.NoDisplay", and then call startActivityForResult() from that. That creates an invisible activity that can both request and receive the intents, before writing data somewhere and then finishing itself.

我知道这是一个较旧的问题,但我遇到了类似的挑战,我的解决方案是使用 android:theme="@android:style/Theme.NoDisplay" 创建一个活动,然后从中调用 startActivityForResult() . 这会创建一个不可见的活动,它可以请求和接收意图,然后在某处写入数据然后自行完成。

回答by Pomagranite

I think the solution is to start the activity from your service then have the activity bind to the service and register a callback

我认为解决方案是从您的服务启动活动,然后将活动绑定到服务并注册回调

回答by 0ne_Up

I know this is an older question, but I've run into a similar challenge, and my solution was to start the activity using startActivity() instead of startActivityForResult(), and using Intent.FLAG_ACTIVITY_NEW_TASK. Then call startService() from the activity instead of setResult(), then use onStartCommand() instead of onActivityResult().

我知道这是一个较旧的问题,但我遇到了类似的挑战,我的解决方案是使用 startActivity() 而不是 startActivityForResult() 并使用 Intent.FLAG_ACTIVITY_NEW_TASK 来启动活动。然后从活动中调用 startService() 而不是 setResult(),然后使用 onStartCommand() 而不是 onActivityResult()。

Binding to the service as @Pomagranite suggested could also work, but that seems more complicated :)

按照@Pomagranite 的建议绑定到服务也可以,但这似乎更复杂:)