[Huawei Developers] HMS Community:
Introduction

In this article, we can learn how to integrate Rewarded Ads feature of Huawei Ads Kit into the android app. So, Rewarded ads are full-screen video ads that allow users to view in exchange for in-app rewards.

Ads Kit

Huawei Ads provides to developers a wide-ranging capabilities to deliver good quality ads content to users. This is the best way to reach the target audience easily and can measure user productivity. It is very useful when we publish a free app and want to earn some money from it.

HMS Ads Kit has 7 types of Ads kits. Now we can implement Rewarded Ads in this application.

Requirements

1. Any operating system (MacOS, Linux and Windows).

2. Must have a Huawei phone with HMS 4.0.0.300 or later.

3. Must have a laptop or desktop with Android Studio, Jdk 1.8, SDK platform 26 and Gradle 4.6 and above installed.

4. Minimum API Level 24 is required.

5. Required EMUI 9.0.0 and later version devices.

How to integrate HMS Dependencies

1. First register as Huawei developer and complete identity verification in Huawei developers website, refer to register a Huawei ID.

2. Create a project in android studio, refer Creating an Android Studio Project.

3. Generate a SHA-256 certificate fingerprint.

4. To generate SHA-256 certificate fingerprint. On right-upper corner of android project click Gradle, choose Project Name > Tasks > android, and then click signingReport, as follows.

Note: Project Name depends on the user created name.

5. Create an App in AppGallery Connect.

6. Download the agconnect-services.json file from App information, copy and paste in android Project under app directory, as follows.

7. Enter SHA-256 certificate fingerprint and click Save button, as follows.

Note: Above steps from Step 1 to 7 is common for all Huawei Kits.

8. Add the below maven URL in build.gradle(Project) file under the repositories of buildscript, dependencies and allprojects, refer Add Configuration.

maven { url 'http://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.6.0.300'

9. Add the below plugin and dependencies in build.gradle(Module) file.

apply plugin: id 'com.huawei.agconnect'
// Huawei AGC
implementation 'com.huawei.agconnect:agconnect-core:1.6.0.300'
// Huawei Ads Kit
implementation 'com.huawei.hms:ads-lite:13.4.51.300'

10. Now Sync the gradle.

11. Add the required permission to the AndroidManifest.xml file.

// Ads Kit
<uses-permission android:name="android.permission.INTERNET" />

Let us move to development

I have created a project on Android studio with empty activity let us start coding.

In the MainActivity.kt we can find the business logic for Ads.

class MainActivity : AppCompatActivity() {

companion object {
private const val PLUS_SCORE = 1
private const val MINUS_SCORE = 5
private const val RANGE = 2
}
private var rewardedTitle: TextView? = null
private var scoreView: TextView? = null
private var reStartButton: Button? = null
private var watchAdButton: Button? = null
private var rewardedAd: RewardAd? = null
private var score = 1
private val defaultScore = 10

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

title = getString(R.string.reward_ad)
rewardedTitle = findViewById(R.id.text_reward)
rewardedTitle!!.setText(R.string.reward_ad_title)

// Load a rewarded ad.
loadRewardAd()

// Load a score view.
loadScoreView()

// Load the button for watching a rewarded ad.
loadWatchButton()

// Load the button for starting a game.
loadPlayButton()

}

// Load a rewarded ad.
private fun loadRewardAd() {
if (rewardedAd == null) {
rewardedAd = RewardAd(this@MainActivity, getString(R.string.ad_id_reward))
}
val rewardAdLoadListener: RewardAdLoadListener = object : RewardAdLoadListener() {
override fun onRewardAdFailedToLoad(errorCode: Int) {
showToast("onRewardAdFailedToLoad errorCode is :$errorCode");
}
override fun onRewardedLoaded() {
showToast("onRewardedLoaded")
}
}
rewardedAd!!.loadAd(AdParam.Builder().build(), rewardAdLoadListener)
}

// Display a rewarded ad.
private fun rewardAdShow() {
if (rewardedAd!!.isLoaded) {
rewardedAd!!.show(this@MainActivity, object : RewardAdStatusListener() {
override fun onRewardAdClosed() {
showToast("onRewardAdClosed")
loadRewardAd()
}
override fun onRewardAdFailedToShow(errorCode: Int) {
showToast("onRewardAdFailedToShow errorCode is :$errorCode")
}
override fun onRewardAdOpened() {
showToast("onRewardAdOpened")
}
override fun onRewarded(reward: Reward) {
// You are advised to grant a reward immediately and at the same time, check whether the reward
// takes effect on the server. If no reward information is configured, grant a reward based on the
// actual scenario.
val addScore = if (reward.amount == 0) defaultScore else reward.amount
showToast("Watch video show finished , add $addScore scores")
score += addScore
setScore(score)
loadRewardAd()
}
})
}
}

// Set a Score
private fun setScore(score: Int) {
scoreView!!.text = "Score:$score"
}

// Load the button for watching a rewarded ad
private fun loadWatchButton() {
watchAdButton = findViewById(R.id.show_video_button)
watchAdButton!!.setOnClickListener(View.OnClickListener { rewardAdShow() })
}

// Load the button for starting a game
private fun loadPlayButton() {
reStartButton = findViewById(R.id.play_button)
reStartButton!!.setOnClickListener(View.OnClickListener { play() })
}

private fun loadScoreView() {
scoreView = findViewById(R.id.score_count_text)
scoreView!!.text = "Score:$score"
}

// Used to play a game
private fun play() {
// If the score is 0, a message is displayed, asking users to watch the ad in exchange for scores.
if (score == 0) {
Toast.makeText(this@MainActivity, "Watch video ad to add score", Toast.LENGTH_SHORT).show()
return
}
// The value 0 or 1 is returned randomly. If the value is 1, the score increases by 1. If the value is 0, the
// score decreases by 5. If the score is a negative number, the score is set to 0.
val random = Random().nextInt(RANGE)
if (random == 1) {
score += PLUS_SCORE
Toast.makeText(this@MainActivity, "You win！", Toast.LENGTH_SHORT).show()
} else {
score -= MINUS_SCORE
score = if (score < 0) 0 else score
Toast.makeText(this@MainActivity, "You lose！", Toast.LENGTH_SHORT).show()
}
setScore(score)
}

private fun showToast(text: String) {
runOnUiThread {
Toast.makeText(this@MainActivity, text, Toast.LENGTH_SHORT).show()
}
}

}

In the activity_main.xml we can create the UI screen.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/text_reward"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:textAlignment="center"
android:textSize="20sp"
android:text="This is rewarded ads sample"/>

<Button
android:id="@+id/play_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/text_reward"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Play" />

<Button
android:id="@+id/show_video_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/play_button"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Watch Video" />

<TextView
android:id="@+id/score_count_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/show_video_button"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

Demo

Tips and Tricks

1. Make sure you are already registered as Huawei developer.

2. Set minSDK version to 24 or later, otherwise you will get AndriodManifest merge issue.

3. Make sure you have added the agconnect-services.json file to app folder.

4. Make sure you have added SHA-256 fingerprint without fail.

5. Make sure all the dependencies are added properly.

Conclusion

In this article, we have learned how to integrate the Huawei Analytics Kit and Ads Kit in Book Reading app. So, I will provide the series of articles on this Book Reading App, in upcoming articles will integrate other Huawei Kits.

I hope you have read this article. If you found it is helpful, please provide likes and comments.

Reference

Ads Kit - Rewarded Ads

Ads Kit – Training Video