これを行うエレガントな方法がわからないところまで来ました。
私がFragment
、 named FragmentA
、およびService
namedを持っているとしましょうBackupService
私はそれを次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
たとえば、同じフラグメントの投稿とイベントの受信 (自分自身への投稿) になります。
フラグメントがバインドされているときに実行中のサービスの参照を取得するエレガントな方法はありますか? このケースにはパターンがあると確信していますが、これまでのところ、ここでグーグル検索して検索してきました。