Android service worker thread launches activity an

2019-06-08 08:40发布

问题:

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