将活动传递给服务或使用BroadCast

时间:2013-03-31 09:02:04

标签: android service android-activity

我有一个本地Service和一个Activity。我想将Activity对象传递给service,因此当Activity绑定到Service时,我可以调用函数activty.doSomething()。我应该这样做吗?我知道我可以使用BroadcastReceiverdoSomething()拨打Service,但与上述想法相比,最佳方法是什么?将activity传递给service或使用BroadcastReceiver?谢谢大家!

// 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
}

1 个答案:

答案 0 :(得分:1)

将活动绑定到服务对于本地服务来说是一种更灵活的选择,因为您可以在两个方向上实现丰富的api。查看documentation here

另一方面,BroadcastReceiver是intentservices的更好选择,因为它们在完成工作后就会过期。

还要记住,如果您希望服务保持不变,则必须使用startService显式启动它,否则当绑定活动的数量变为0时它将被终止。