[英]How to use EventBus between activities in android
在我的申請中,我有兩項 activities
。
活動A和活動B。
進入活動B我有一個dialog
,當用戶單擊此dialog
的按鈕之一時,我想將方法調用到活動A中
我寫下面的代碼,但是當單擊dialog
按鈕時,不調用Activity A中的方法。
活動B對話代碼:
vipDialog = new Dialog(context);
vipDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
vipDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
vipDialog.setContentView(R.layout.base_dialog);
//Set cancellable
vipDialog.setCancelable(false);
//Init views
baseDialog_logo = vipDialog.findViewById(R.id.baseDialog_logo);
baseDialog_title = vipDialog.findViewById(R.id.baseDialog_title);
baseDialog_desc = vipDialog.findViewById(R.id.baseDialog_desc);
baseDialog_negativeBtn = vipDialog.findViewById(R.id.baseDialog_negativeBtn);
baseDialog_positiveBtn = vipDialog.findViewById(R.id.baseDialog_positiveBtn);
baseDialog_buttonsLay = vipDialog.findViewById(R.id.baseDialog_buttonsLay);
baseDialog_cancelBtn = vipDialog.findViewById(R.id.baseDialog_cancelBtn);
//Set weight
baseDialog_buttonsLay.setWeightSum(2);
baseDialog_cancelBtn.setVisibility(View.GONE);
//Set logo
baseDialog_logo.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.dialog_vip_logo));
//Set text
baseDialog_title.setText(getString(R.string.trialTitle));
baseDialog_desc.setText(getString(R.string.trialDesc));
baseDialog_positiveBtn.setText(getString(R.string.buyVip));
baseDialog_negativeBtn.setText(getString(R.string.detailSeeAdv));
//Set click listeners
baseDialog_positiveBtn.setOnClickListener(v -> {
EventBus.getDefault().post(new BuyPremiumUserEvent(true));
finish();
});
baseDialog_negativeBtn.setOnClickListener(v -> {
loadFullPageAdv(getViewContext(), BuildConfig.fullPageDetailApiKey, TapsellAdRequestOptions.CACHE_TYPE_STREAMED);
});
vipDialog.show();
活動A代碼:
@Override
protected void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
protected void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onBuyPremium(final BuyPremiumUserEvent event) {
clickedOnBuyPremium = event.isClickOnBuyPremium();
initBazaarUserRegistered();
Log.e("paymentLog", "Clicked");
}
當單擊對話框時,不顯示Log.e("paymentLog", "Clicked");
進入日志。
我該如何解決?
您可能需要使用粘性事件。 由於在Activity A
啟動Activity B
它將轉到后台,並且不再接收任何事件。
將其放在您的Activity A
而不是EventBus.getDefault().register(this)
@Override
public void onStart() {
super.onStart();
EventBus.getDefault().registerSticky(this);
}
而且您還需要發布此類粘性事件
EventBus.getDefault().postSticky(new BuyPremiumUserEvent(true));
然后在您的訂閱服務器中,像這樣添加sticky作為true
@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void onBuyPremium(final BuyPremiumUserEvent event) {
clickedOnBuyPremium = event.isClickOnBuyPremium();
initBazaarUserRegistered();
Log.e("paymentLog", "Clicked");
}
這是粘性事件的文檔
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.