简体   繁体   中英

How to use EventBus just for first time in Android

In my application i have 2 activity . Activity A and Activity B .
For show Activity B users should go to from Activity A .
In activity B i have one button and i want when click on this button finish Activity B and call one method into Activity A .
For this work i write below code :

       baseDialog_positiveBtn.setOnClickListener(v -> {
            EventBus.getDefault().postSticky(new BuyPremiumUserEvent(true));
            finish();
        });

And for call method into Activity A i write below code :

@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void onBuyPremium(final BuyPremiumUserEvent event) {
    clickedOnBuyPremium = event.isClickOnBuyPremium();
    Log.e("clickedOnBuyPremium", "Event : " + clickedOnBuyPremium);
    if (AppConstant.getInstance().isPackageInstalled(AppConstant.BAZAAR_PAYMENT_PACKAGE, packageManager)) {
        initBazaarUserRegistered();
    } else {
        AppConstant.getInstance().showMessage(activity, getString(R.string.errorTitle),
                getString(R.string.notInstalledBazaar), R.color.catRedColor);
    }
}

When click on Button , call above method!
But when click on Button , call Activity A methods always!
My mean is : after click on button , even go to Activity C , E and more ... and when click on back button for go to Activity A again call above method of Activity A .
I want call above method just when click on button from Activity B , not always!

How can i fix it?

If I correctly understood your situation - you have a button in one activity that initiates an eventBus event, and a second activity-subscriber to this event.

And after button is clicked, you run some registration wizard on another activity, but your problem is that this subscribed method called on other events too, that you don't want to handle in a such way. Is this correct?

Actually, I don't see a point to use eventBus in a such case. If you just want to show Activity B from Activity A , when button is clicked, then just show your activity using Intent instance:

Intent intent = new Intent(this, ActivityB.class)
startActivity(intent)

I could misunderstand you. Can you add more details about your situation?

If you need to use eventBus, then maybe your multiple calls of subscribed events is the cause of making event sticky . Try the same with usual events:

 baseDialog_positiveBtn.setOnClickListener(v -> {
            EventBus.getDefault().post(new BuyPremiumUserEvent(true));
            finish();
        });

And handle them without sticky flag:

@Subscribe(threadMode = ThreadMode.MAIN)
public void onBuyPremium(final BuyPremiumUserEvent event) {
  //...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM