mario595
mario595

Reputation: 3761

How to pass an Activity in an Intent

I am trying to implement the delegate pattern for inform to the UI of the process of a async operation. So I have an interface like that:

public interface UpdateLibraryDelegate {
    public void startDownloadingLibrary();
    public void endDownloadingLibrary();
    public void processingLibrary(int progress);
    public void endProcessingLibrary();
}

I have an Activity :

public class HomeActivity implements UpdateLibraryDelegate{

   protected void onCreate(Bundle savedInstanceState) {
         ...
          Intent libraryIntent = new Intent(this, MyService.class);
          /*Here is where the problem is*/
          libraryIntent.putExtra(UPDATE_LIBRARY_DELEGATE, this);
         ...
   }

  /*Methods of the interface*/
  ...
  /**/
}

The problem obviously is that I can't send my activity in the intent since it isn't either Serializable or Parcelable. Is there any way to send the activity with the Intent? It is stupid what I am trying to do and there is a more reasonable way to do that? I am completely new on Android...

Thanks!

Upvotes: 0

Views: 527

Answers (2)

Agustin
Agustin

Reputation: 114

You have to use the AsyncTask class to perform async operations.

Watch here for the class usage.

And here for an example.

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1006664

Is there any way to send the activity with the Intent?

No.

It is stupid what I am trying to do and there is a more reasonable way to do that?

The contract pattern is perfectly fine, just not for activity<->service communication using the command pattern. That is a loose-coupling pattern, which runs counter to the contract (what you are calling the delegate) pattern.

Moreover, if you are using the command pattern with a service, the reason for having the service in the first place is because the activity can go away, while the service wraps up its bit of work. That is why loose coupling is used here.

The more typical approach for services is to use message passing:

  • LocalBroadcastManager
  • a third-party event bus, like Square's Otto
  • a Messenger
  • etc.

to have the service raise events that the activity can subscribe to, if the activity exists.

If the service will only be around while the activity is, you may wish to reconsider why you have the service in the first place. If there are legitimate needs for the service, you could use the binding pattern (bindService()), in which case you can carefully use your contract/delegate pattern.

Upvotes: 2

Related Questions