Kingfisher Phuoc
Kingfisher Phuoc

Reputation: 8190

Pass Activity to service or use BroadCast

I have a local Service and an Activity. I want to pass Activity object to service, so when Activity is bound to my Service, I can call function activty.doSomething(). Should I do it? I know that I can use BroadcastReceiver to call doSomething() from Service, but comparing with the above idea, what is the best way to do? Pass activity to service or use BroadcastReceiver? Thank everyone!

// This is MyActivity, where I will pass `activity` to `service` when `service` 
//  is bound or when activity is resumed. I will clear the `activity` object 
//  in `Service` when `Activity` is paused.
public class MyActivity extends Activity{

    LocalService mService; // this is my 

    @Override
    public void onResume(){
        if(isServiceBound){
            mService.setActivity(this);
        }
    }

    public void onPause(){
        if(isServiceBound){
            mService.setActivity(null);
        }
    }

    // Do something here
    public void doSomething(){
    }

    //Code to start, bind service, unbind ... go here

}

public class LocalService extends Service{
    MyActivity mActivity;
    public void setActivity(MyActivity a){
        mActivity = a;
    }
    // Start service, do something here
}

Upvotes: 0

Views: 993

Answers (1)

fedepaol
fedepaol

Reputation: 6862

Binding the activity to the service is a more flexible option for local services, since you can implement a rich api in both directions. Check the documentation here

On the other hand, BroadcastReceiver is a better option for intentservices, because they expire as soon as they finish their job.

Remember also that if you want your service to persist, you have to start it explicitly with startService, otherwise it will be killed when the number of bound activities goes to 0.

Upvotes: 1

Related Questions