0

我有一个本地Service和一个Activity. 我想将Activityobject 传递给service,所以当Activity绑定到 my时Service,我可以调用 function activty.doSomething()。我应该这样做吗?我知道我可以使用BroadcastReceiverto 调用doSomething()from Service,但是与上面的想法相比,最好的方法是什么?传递activityservice还是使用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
}
4

1 回答 1

1

将活动绑定到服务是本地服务更灵活的选择,因为您可以在两个方向上实现丰富的 api。在此处查看文档

另一方面,对于意图服务来说,BroadcastReceiver 是一个更好的选择,因为它们一旦完成工作就会过期。

还要记住,如果你想让你的服务持久化,你必须用 startService 显式启动它,否则当绑定活动的数量变为 0 时它会被杀死。

于 2013-03-31T09:25:39.577 回答