我有一个本地Service
和一个Activity
. 我想将Activity
object 传递给service
,所以当Activity
绑定到 my时Service
,我可以调用 function activty.doSomething()
。我应该这样做吗?我知道我可以使用BroadcastReceiver
to 调用doSomething()
from 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
}