Android service worker thread launches activity and waits a response

怎甘沉沦 提交于 2019-12-10 11:39:12

问题


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

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);
    }

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.

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();
(...)

How can I do it?

Thanks.


回答1:


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. Your Activity can call startService() with the response as an extra in the Intent. This will result in onStartCommand() being called in the Service.

  2. 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.

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



来源:https://stackoverflow.com/questions/21284849/android-service-worker-thread-launches-activity-and-waits-a-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!