我已经到了一个点,我不知道一个优雅的方式来做这件事。
假设我有一个名为FragmentA
的Fragment
和一个名为BackupService
的Service
在FragmentA
上,我使用以下命令将其绑定到BackupService
:
private ServiceConnection backupServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
LocalBinder binder = (LocalBinder) service;
backupBoundService = binder.getService();
isBound = true;
// How to let the fragment know this has happened?
// Use an eventBus? EventBus.getDefault().post(backupBoundService); ?
Log.d(TAG, "On Service Connected -> Yup!");
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
isBound = false;
}
};
和:
Intent intent = new Intent(ApplicationContextProvider.getContext(), BackupsService.class);
ApplicationContextProvider.getContext().bindService(intent, backupServiceConnection, Context.BIND_AUTO_CREATE); // Using application context
现在我知道绑定是一项asynchronous
任务,这就是我的问题所在。
我想出了使用EventBus
的想法,但我并不觉得它优雅,因为片段将发布对象(在本例中为backupBoundService
),引用服务,同时将侦听/接收来自总线的事件,例如,将是相同的片段发布和接收事件(发布给自己)。
当片段被绑定到它时,有没有一种优雅的方法来获取正在运行的服务的引用?我很确定这个案例是有规律的,但是到目前为止,我已经在谷歌上搜索过了,没有找到任何线索。
发布于 2014-06-25 00:54:13
您好,您可以使用eventbus,也可以使用Interfcae创建简单的回调方法来满足您的需求。
如果您没有使用接口创建回调的想法,那么请查看这段代码。它与eventbus相同:)
// The callback interface
interface MyCallback {
void callbackCall();
}
// The class that takes the callback
class Worker {
MyCallback callback;
void onEvent() {
callback.callbackCall();
}
public void setCallBack(MyCallback callback)
this.callback=callback;
}
/////////////////////////////
class Callback implements MyCallback {
....
Worker worker= new Worker()
Worker.setCallback(this);
.. .
void callbackCall() {
// callback code goes here
//onEvent this method will execute
}
}
希望这能对你有所帮助。祝你好运:)
https://stackoverflow.com/questions/24391416
复制相似问题