how does a service return result to an activity

后端 未结 4 456
有刺的猬
有刺的猬 2020-12-24 12:25

I seem to have a classic task, yet I can\'t find any examples on how to do it.

I want to download something. Well I call a web service and get a response... but it\'

相关标签:
4条回答
  • 2020-12-24 13:03

    You can use Pending Intent,Event Bus,Messenger or Broadcast Intents to get data from service back to activity/fragment and then perform some operation on the data.

    My blog post covers all these approaches.

    0 讨论(0)
  • 2020-12-24 13:05

    Send a broadcast Intent with the data via sendBroadcast(), that the activity picks up with a BroadcastReceiver.

    Here's an example of that: https://github.com/commonsguy/cw-android/tree/master/Service/WeatherAPI Doc: http://developer.android.com/reference/android/content/BroadcastReceiver.html

    0 讨论(0)
  • 2020-12-24 13:09

    If you need return various types of data, such as user-defined class, you may try bindService and callback. This can avoid implement parcelable interface than sendBroadcast.

    Please see the example in my post:

    https://stackoverflow.com/a/22549709/2782538

    And more, if you use IntentService, you could look into ResultReceiver. The details and sample could be found in this post:

    Android: restful API service

    Hope it helps.

    0 讨论(0)
  • 2020-12-24 13:11

    According to Google documentation, if your Activity and Service are within the same app, using a LocalBroadcastManager is preferable over sendBroadcast (intent) because the information sent does not go through the system which eliminates the risk of interception.

    It's quite easy to use.

    In your activity, create a BroadcastReceiver and dynamically add a listener in the onResume() method :

    private BroadcastReceiver  bReceiver = new BroadcastReceiver(){
    
        @Override
        public void onReceive(Context context, Intent intent) {
            //put here whaterver you want your activity to do with the intent received
        }           
    };
    
    protected void onResume(){
        super.onResume();
        LocalBroadcastManager.getInstance(this).registerReceiver(bReceiver, new IntentFilter("message"));
    }
    
    protected void onPause (){
        super.onPause();
     LocalBroadcastManager.getInstance(this).unregisterReceiver(bReceiver);
    }
    

    And in your service, you get an instance of LocalBroadcastManager and use it to send an intent. I usually put it in its own method like this :

    private void sendBroadcast (boolean success){
        Intent intent = new Intent ("message"); //put the same message as in the filter you used in the activity when registering the receiver
        intent.putExtra("success", success);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }
    
    0 讨论(0)
提交回复
热议问题