Android: startServiceForResult method

Viewed 603

Is there any call in android sort of, startServiceForResult, just like we have startActivityForResult?

I have created a service to retrieve data from the web APIs and now I want to populate a ListView using that data.

I noticed that using Broadcast Receiver, the only method I have is onReceive, which has void datatype and hence I cannot properly inflate my list with the data I receive.

In case there is no startServiceForResult, will it be valid and would it work properly if I pass a service inside the startActivityForResult method call?

2 Answers

No. Use Broadcasts instead

In your Activity

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

In Service

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

Starting from Android N, broadcast mechanism using LocalBroadcastManager won't work as expected.

Register broadcast using:

context.registerReceiver(receiver, new IntentFilter("MY_ACTION"));

Unregister broadcast using:

context.unregisterReceiver(receiver);

Send broadcast using:

context.sendBroadcast(intent);

https://developer.android.com/about/versions/nougat/android-7.0-changes.html

Related