简体   繁体   中英

How to automatically close reward ad after rewarded [Android-Studio]

So i'm trying to have it automatically close the ad after it rewards the user here is what I got so far.

Keep in mind i'm new to android studio and java as a whole. If they are spaced they are in different methods.

private RewardedVideoAd mAd;

AdView adView;
void init_admob(){
    adView = (AdView) findViewById(R.id.adView);
    AdRequest adRequest = new AdRequest.Builder().setRequestAgent("android_studio:ad_template").build();
    adView.loadAd(adRequest);
    mAd = MobileAds.getRewardedVideoAdInstance(this);
    mAd.setRewardedVideoAdListener(this);
    loadRewardedVideoAd();
}


public void onRewarded(RewardItem reward) {
    Toast.makeText(this, reward.getAmount()+ " " +getString(R.string.points_received), Toast.LENGTH_SHORT).show();
    award(reward.getAmount(),getString(R.string.admob_credit));
    exitAd();
}


public void exitAd() {
    //dispatchKeyEvent(new KeyEvent (KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK)); Tried But didn't work (No Errors Just didn't work)
    //dispatchKeyEvent(new KeyEvent (KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK)); Tried but didn't work (No Errors Just didn't work)
    try {
        LinearLayout linLay = (LinearLayout) findViewById(R.id.adView);
        linLay.removeView(adView);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Error For linLay

java.lang.ClassCastException: com.google.android.gms.ads.AdView cannot be cast to android.widget.LinearLayout

So I don't really know what else to try or how to close the AdView after the ad has rewarded any help is apperciated!

I do not think that is possible. It would also be not right legally. When you show an ad, you should wait for the user to either click or cancel the ad. If you close programmatically, it would mean you have effectively forced the user to cancel the ad. (It may be good for the user, but think from the advertiser's perspective)

You cant close the ad in-app but here is what I have done.

private fun showRewardedVideo() {
    if (mRewardedAd.isLoaded) {
      mRewardedAd.show(
              this,
              object : RewardedAdCallback() {
                  override fun onUserEarnedReward(
                          rewardItem: RewardItem
                  ) {
                      Toast.makeText(this@MainActivity, "onUserEarnedReward", Toast.LENGTH_LONG).show()
                      addCoins(rewardItem.amount)
                     // come back to ad activity
                      startActivity(Intent(this@MainActivity, MainActivity2::class.java))
                  }

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