Rewarded Ads in Kotlin with XML UI

Here's a step-by-step example of implementing Rewarded Ads in Kotlin with XML UI:

### 1. Add AdMob Dependency
In your `build.gradle` (Module level):
```gradle
dependencies {
    implementation 'com.google.android.gms:play-services-ads:22.6.0'
}
```

### 2. Update AndroidManifest.xml
Add these permissions and metadata:
```xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application>
    <meta-data
        android:name="com.google.android.gms.ads.APPLICATION_ID"
        android:value="ca-app-pub-3940256099942544~3347511713"/> <!-- Test ID -->
</application>
```

### 3. Create XML Layout (activity_main.xml)
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center">

    <Button
        android:id="@+id/btnShowAd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Rewarded Ad"
        android:enabled="false"/>

    <TextView
        android:id="@+id/tvStatus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Loading ad..."
        android:layout_marginTop="16dp"/>
</LinearLayout>
```

### 4. Implement Rewarded Ad Code (MainActivity.kt)
```kotlin
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.MobileAds
import com.google.android.gms.ads.rewarded.RewardedAd
import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback
import com.google.android.gms.ads.rewarded.RewardItem
import com.google.android.gms.ads.rewarded.RewardedAdCallback

class MainActivity : AppCompatActivity() {
    private var rewardedAd: RewardedAd? = null
    private lateinit var btnShowAd: Button
    private lateinit var tvStatus: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btnShowAd = findViewById(R.id.btnShowAd)
        tvStatus = findViewById(R.id.tvStatus)

        // Initialize Mobile Ads SDK
        MobileAds.initialize(this) {
            loadRewardedAd()
        }

        btnShowAd.setOnClickListener {
            showRewardedAd()
        }
    }

    private fun loadRewardedAd() {
        val adRequest = AdRequest.Builder().build()
        val adUnitId = "ca-app-pub-3940256099942544/5224354917" // Test ID

        RewardedAd.load(this, adUnitId, adRequest, object : RewardedAdLoadCallback() {
            override fun onAdLoaded(ad: RewardedAd) {
                rewardedAd = ad
                btnShowAd.isEnabled = true
                tvStatus.text = "Ad loaded!"
            }

            override fun onAdFailedToLoad(errorCode: Int) {
                tvStatus.text = "Ad failed to load: $errorCode"
                btnShowAd.isEnabled = false
            }
        })
    }

    private fun showRewardedAd() {
        rewardedAd?.let { ad ->
            ad.show(this, object : RewardedAdCallback() {
                override fun onUserEarnedReward(reward: RewardItem) {
                    // Handle reward here
                    val rewardAmount = reward.amount
                    val rewardType = reward.type
                    Toast.makeText(
                        this@MainActivity,
                        "Earned $rewardAmount $rewardType",
                        Toast.LENGTH_SHORT
                    ).show()
                }

                override fun onRewardedAdClosed() {
                    loadRewardedAd() // Load a new ad after closing
                    btnShowAd.isEnabled = false
                    tvStatus.text = "Ad closed - loading new ad..."
                }

                override fun onRewardedAdFailedToShow(errorCode: Int) {
                    tvStatus.text = "Ad failed to show: $errorCode"
                }
            })
        } ?: run {
            tvStatus.text = "Ad not loaded yet"
        }
    }

    override fun onDestroy() {
        rewardedAd = null
        super.onDestroy()
    }
}
```

### Key Features:
1. Ad Loading: Automatically loads a rewarded ad on app start
2. UI Integration: Button is enabled only when ad is loaded
3. Reward Handling: Shows reward amount when user completes ad
4. Ad Reloading: Automatically loads new ad after previous one is closed
5. Error Handling: Shows error messages in UI

### Test Ads:
- Use the provided test ad unit IDs during development
- Replace with your actual ad unit IDs before publishing
- Never click your own live ads

### Important Notes:
1. Make sure you have proper internet permissions
2. Use test ads during development to avoid account suspension
3. Handle ad lifecycle properly (especially in onDestroy)
4. Follow AdMob policies for rewarded ads placement
5. Consider user experience when deciding when to show ads

This example shows a basic implementation. You might want to add:
- Loading indicators
- Retry logic for failed loads
- Cooldown periods between ads
- Proper reward handling for your app's use case

Comments

Popular posts from this blog

Kotlin Math Operations and Functions Overview

Kotlin Strings: Features and Operations Guide

Kotlin Android Program (QCR) Application Codes That Read Text in Photos