Android Service Worker线程启动活动并等待响应 [英] Android service worker thread launches activity and waits a response

查看:213
本文介绍了Android Service Worker线程启动活动并等待响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一项在启动时启动的服务,应在设备打开时运行.

I have a service that starts on boot and should run while the device is on.

此服务具有一个工作线程,当某个事件发生时,该工作线程会启动活动(QueryActivity).此活动是通过意图启动的:

This service has a worker thread that launches an activity (QueryActivity) when a certain event takes place. This activity is launched trough an intent:

private void launchActivity(String msg){
        Intent intent = new Intent(getBaseContext(), QueryActivity.class);
        intent.putExtra("query", msg);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getApplication().startActivity(intent);
    }

该活动将显示基于额外传递的String msg的文本视图.该活动也显示两个按钮.假设是和否按钮.用户阅读该文本,然后单击是"或否".

The activity will display a text view based on the String msg passed as extra. The activity displays two buttons as well. Let's say YES and NO buttons. The user reads the text and clicks either YES or NO.

我想在launchActivity方法之后,在工作线程中立即将用户的选择(是或否)发送回服务.

I want to send the user's choice (yes or no) back to the service, immediately after the launchActivity method, inside the worker thread.

(...)
launchActivity(str);
String YesOrNo = receiveUserChoice();
(...)

我该怎么办?

谢谢.

推荐答案

您无法从服务启动活动"并立即获得响应.响应将需要异步返回.有几种方法可以做到这一点:

You can't launch the Activity from your Service and get an immediate response. The response will need to come back asynchronously. There are several ways to do this:

  1. 您的活动可以调用startService(),并在Intent中作为附加响应.这将导致在服务中调用onStartCommand().

  1. Your Activity can call startService() with the response as an extra in the Intent. This will result in onStartCommand() being called in the Service.

活动可以发送包含响应的本地广播Intent.在这种情况下,服务需要设置BroadcastReceiver来侦听响应.

The Activity can send a local broadcast Intent containing the response. In that case the Service needs to set up a BroadcastReceiver to listen for the response.

活动可以绑定到服务,并按照@ njzk2的建议将数据传递回去(尽管这有点复杂).

Activity can bind to the Service and pass the data back as @njzk2 suggested (this is a bit more complicated though).

这篇关于Android Service Worker线程启动活动并等待响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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