The Huawei Search Kit provide awesome capabilities to build your own search engine or even go beyond. With Search Kit you can add a mini web browser to your app app with web searching capabilities, by this way, the user will be able to surf into the Internet without knowing the complete URL of the website. In this article we will build a Web Browser application powered by Search Kit.
Previous Requirements
A verified developer account
A configured project in AppGallery Connect
Configuring and adding the Search Kit
Once you have propely configured you project in AGC, go to "Manage APIs" from your project settings and enable Search Kit.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Note: Search Kit require to choose a Data Storage Location, make sure to choose a DSL which support the countries where you plan to release your app.
Once you have enabled the API and choosen the Data Storage Location, download (or re-download) you agconnect-services.json and add it to your Android Project. Then, add the Serach Kit latest dependency to your app-level build.gradle file, we will also need the related dependencies of coroutines and data binding.
Code:
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.2.0"
implementation "android.arch.lifecycle:extensions:1.1.1"
implementation 'com.huawei.agconnect:agconnect-core:1.4.2.301'
implementation 'com.huawei.hms:searchkit:5.0.4.303'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.9'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9'
Initializing the SDK
Before using Search Kit, you must apply for an access token, in order to authenticate the requests yo made by using the kit. If you don't provide the proper credentials, Search Kit will not work.
To get your Access Token, perform the next POST request:
Endpoint:
https://oauth-login.cloud.huawei.com/oauth2/v3/token
Headers:
content-type: application/x-www-form-urlencoded
Body:
"grant_type=client_credentials&client_secret=APP_SECRET&client_id=APP_ID"
Your App Id and App Secret will be available from your App dashboard in AGC
Note: Before sending the request, you must encode your AppSecret with URLEncode.
In order to perform the token request, let's create a request helper
HTTPHelper.kt
Code:
object HTTPHelper {
fun sendHttpRequest(
url: URL,
method: String,
headers: HashMap<String, String>,
body: ByteArray
): String {
val conn = url.openConnection() as HttpURLConnection
conn.apply {
requestMethod = method
doOutput = true
doInput = true
for (key in headers.keys) {
setRequestProperty(key, headers[key])
}
if(method!="GET"){
outputStream.write(body)
outputStream.flush()
}
}
val inputStream = if (conn.responseCode < 400) {
conn.inputStream
} else conn.errorStream
return convertStreamToString(inputStream).also { conn.disconnect() }
}
private fun convertStreamToString(input: InputStream): String {
return BufferedReader(InputStreamReader(input)).use {
val response = StringBuffer()
var inputLine = it.readLine()
while (inputLine != null) {
response.append(inputLine)
inputLine = it.readLine()
}
it.close()
response.toString()
}
}
}
We will take advantage of the Kotlin Extensions to add the token request to the SearchKitInstance class, if we initialize the Search Kit from the Application Class, a fresh token will be obtained upon each app startup. When you have retrieved the token, call the method SearchKitInstance.getInstance().setInstanceCredential(token)
BrowserApplication.kt
Code:
class BrowserApplication : Application() {
companion object {
const val TOKEN_URL = "https://oauth-login.cloud.huawei.com/oauth2/v3/token"
const val APP_SECRET = "YOUR_OWN_APP_SECRET"
}
override fun onCreate() {
super.onCreate()
val appID = AGConnectServicesConfig
.fromContext(this)
.getString("client/app_id")
SearchKitInstance.init(this, appID)
CoroutineScope(Dispatchers.IO).launch {
SearchKitInstance.instance.refreshToken([email protected])
}
}
}
fun SearchKitInstance.refreshToken(context: Context) {
val config = AGConnectServicesConfig.fromContext(context)
val appId = config.getString("client/app_id")
val url = URL(BrowserApplication.TOKEN_URL)
val headers = HashMap<String, String>().apply {
put("content-type", "application/x-www-form-urlencoded")
}
val msgBody = MessageFormat.format(
"grant_type={0}&client_secret={1}&client_id={2}",
"client_credentials", URLEncoder.encode(APP_SECRET, "UTF-8"), appId
).toByteArray(Charsets.UTF_8)
val response = HTTPHelper.sendHttpRequest(url, "POST", headers, msgBody)
Log.e("token", response)
val accessToken = JSONObject(response).let {
if (it.has("access_token")) {
it.getString("access_token")
} else ""
}
setInstanceCredential(accessToken)
}
In short words, the basic setup of Search Kit is as follows:
Init the service, by calling SearchKitInstance.init(Context, appID)
Rerieve an App-Level access token
Call SearchKitInstance.getInstance().setInstanceCredential(token) to specify the access token which Search Kit will use to authenticate the requests
Auto Complete Widget
Let's create a custom widget wich can be added to any Activity or Fragment, this widget will show some search suggestions to the user when begins to write in the search bar.
First, we must design the Search Bar, it will contain an Image View and an Edit Text.
view_search.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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="wrap_content"
android:background="@drawable/gray_rec"
android:paddingHorizontal="5dp"
android:paddingVertical="5dp"
>
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/ic_menu_search"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@android:drawable/ic_menu_search" />
<EditText
android:id="@+id/textSearch"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/imageView"
app:layout_constraintTop_toTopOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
Now is time to create the widget layout, it will contain our search bar and a recycler view to show the suggestions
More details, you can check https://forums.developer.huawei.com/forumPortal/en/topic/0202455305475510024
Related
In this article, I will try to explain how you can easily implement Huawei Banner Ads to your project and monetize your application right away!
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
What is Banner Ad
Banner ads are rectangular images that can be placed to the top, middle, or bottom of your app’s screen. Banner ads refresh automatically at regular intervals. When a user taps a banner ad, the user is redirected to the advertiser’s page in most cases.
To implement banner ads, you need to implement Huawei Ads Kit dependency to your project which I explained below.
How to Implement Ads Kit
Things you need to have
1) A Huawei Developer Account (It needs to be Enterprise Level account for monetization)
2) A Huawei phone with HMS 4.0.0.300 or later
3) A computer with Android Studio , Jdk 1.8, SDK platform 26 and Gradle 4.6 installed.
Things Need To Be Done Before Implementation
First things first HMS Core needs to be implemented to the your project. To see how to implement HMS Core please refer this link.
After HMS Core implementation, Ads Kit dependency needs to be added in app level “build.gradle” file
Code:
dependencies {
...
//Huawei Ads Kit Dependency
implementation 'com.huawei.hms:ads-lite:13.4.32.300'
...
}
4) Configure obfuscation scripts to prevent HUAWEI Ads kit from being obfuscated. Add the following two lines of code to the app/proguard-rules.pro
Code:
-keep class com.huawei.openalliance.ad.** { *; }
-keep class com.huawei.hms.ads.** { *; }
After Completing the steps above. All you need to do is initialize Huwei Ads by calling HwAds.init() method in your application. Then the application is ready to implement all kind of various ad types which I will show below.
Code:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
...
// Initialize the HUAWEI Ads SDK.
HwAds.init(this);
...
}
Implementing Banner Ads
To implement Banner Ad, BannerView object needs to be initialized either with XML or directly in code.
Adding Banner Ads Through XML
Create BannerView in your XML
Code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:hwads="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=".BannerAdsActivity">
...
<!--Adding BannerView Through XML-->
<com.huawei.hms.ads.banner.BannerView
android:id="@+id/hwBannerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
hwads:adId="testw6vs28auh3"
hwads:layout_constraintEnd_toEndOf="parent"
hwads:layout_constraintStart_toStartOf="parent"
hwads:layout_constraintTop_toTopOf="parent"
hwads:bannerSize="BANNER_SIZE_360_57"
/>
...
</androidx.constraintlayout.widget.ConstraintLayout>
Call it from your class & load the add.
Code:
override fun onCreate(savedInstanceState: Bundle?) {
....
// Obtain BannerView based on the configuration in XML layout.
val adParam = AdParam.Builder().build();
hwBannerView.loadAd(adParam);
...
}
Run the application and the result will be like below.
Adding Banner Ads Programmatically Without XML
Lets create another Banner ad at the bottom of our view without using XML. All you need to do is creating & initializing banner ad , adding it to the specific layout, then loading the ad as below.
Code:
override fun onCreate(savedInstanceState: Bundle?) {
...
val adParam = AdParam.Builder().build();
val bannerView = BannerView(this);
// "testw6vs28auh3" is a dedicated test ad slot ID. To get real one, you need to have an enterprise level Huawei developer account.
bannerView.setAdId("testw6vs28auh3");
bannerView.setBannerAdSize(BannerAdSize.BANNER_SIZE_320_50);
val parentLayout = findViewById<ConstraintLayout>(R.id.clBannerMain);
val set = ConstraintSet();
// set view id, else getId() returns -1
bannerView.id = View.generateViewId()
parentLayout.addView(bannerView,0)
set.clone(parentLayout)
set.connect(bannerView.id, ConstraintSet.BOTTOM, parentLayout.id, ConstraintSet.BOTTOM, 0);
set.applyTo(parentLayout);
bannerView.loadAd(adParam)
...
}
As shown above, we have successfully added second banner ad to our program without touching the xml.
Optional: Adding Ad Listener
After implementing banner ads to your project, if you want to proceed further, you can add Ad listener to listen ad events like is AdLoaded is AdFailed is AdClicked etc.
Code:
override fun onCreate(savedInstanceState: Bundle?) {
...
val adListener = object : AdListener() {
override fun onAdImpression() {
super.onAdImpression()
}
override fun onAdFailed(p0: Int) {
super.onAdFailed(p0)
}
override fun onAdLeave() {
super.onAdLeave()
}
override fun onAdClicked() {
super.onAdClicked()
}
override fun onAdClosed() {
super.onAdClosed()
}
override fun onAdOpened() {
super.onAdOpened()
}
override fun onAdLoaded() {
super.onAdLoaded()
}
}
//Add Ad Listener to which ad you want to listen.
bannerView.adListener = adListener
....
}
As you can see, it is really easy to implement banner ads to your android application with Huawei Ads Kit. Stay tuned for other ad types. You can find the github project below.
Resources
https://github.com/Disav0wed/Huawei_Banner_Ads_Demo
https://developer.huawei.com/consumer/en/doc/development/HMS-Guides/ads-sdk-guide-banner
https://developer.huawei.com/consumer/en/codelab/HUAWEIAdsSDK-BannerAds/index.html#2
Related Links
Thanks to Ibrahim R. Serpici for this article.
Original post: https://medium.com/huawei-developers/huawei-ads-kit-banner-ads-1130da8d40da
In this article, I will try to explain how you can easily implement Huawei Banner Ads (In Kotlin) to your project and monetize your application right away!
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
What is Banner Ad
Banner ads are rectangular images that can be placed to the top, middle, or bottom of your app’s screen. Banner ads refresh automatically at regular intervals. When a user taps a banner ad, the user is redirected to the advertiser’s page in most cases.
To implement banner ads, you need to implement Huawei Ads Kit dependency to your project which I explained below.
How to Implement Ads Kit
Things you need to have
1) A Huawei Developer Account (It needs to be Enterprise Level account for monetization)
2) A Huawei phone with HMS 4.0.0.300 or later
3) A computer with Android Studio , Jdk 1.8, SDK platform 26 and Gradle 4.6 installed.
Things Need To Be Done Before Implementation
First things first HMS Core needs to be implemented to the your project.
After HMS Core implementation, Ads Kit dependency needs to be added in app level “build.gradle” file
Code:
<pre class="brush:java;toolbar:false;">dependencies {
...
//Huawei Ads Kit Dependency
implementation 'com.huawei.hms:ads-lite:13.4.32.300'
...
} </pre><p style="white-space: normal;">
</p><p style="white-space: normal;">4) Configure obfuscation scripts to prevent HUAWEI Ads kit from being obfuscated. Add the following two lines of code to the <strong>app/proguard-rules.pro</strong></p><p style="white-space: normal;"><strong>
</strong></p><pre class="brush:java;toolbar:false">-keep class com.huawei.openalliance.ad.** { *; }
-keep class com.huawei.hms.ads.** { *; }
</pre><p style="white-space: normal;">
</p><p style="white-space: normal;">After Completing the steps above. All you need to do is initialize Huwei Ads by calling HwAds.init() method in your application. Then the application is ready to implement all kind of various ad types which I will show below.</p><pre class="brush:java;toolbar:false">override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
...
// Initialize the HUAWEI Ads SDK.
HwAds.init(this);
...
} </pre>
Implementing Banner Ads
To implement Banner Ad, BannerView object needs to be initialized either with XML or directly in code.
Adding Banner Ads Through XML
Create BannerView in your XML
Code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:hwads="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=".BannerAdsActivity">
...
<!--Adding BannerView Through XML-->
<com.huawei.hms.ads.banner.BannerView
android:id="@+id/hwBannerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
hwads:adId="testw6vs28auh3"
hwads:layout_constraintEnd_toEndOf="parent"
hwads:layout_constraintStart_toStartOf="parent"
hwads:layout_constraintTop_toTopOf="parent"
hwads:bannerSize="BANNER_SIZE_360_57"
/>
...
</androidx.constraintlayout.widget.ConstraintLayout>
After creating the your BannerView through XML file, call it from your class & load the add.
Code:
override fun onCreate(savedInstanceState: Bundle?) {
....
// Obtain BannerView based on the configuration in XML layout.
val adParam = AdParam.Builder().build();
hwBannerView.loadAd(adParam);
...
}
Run the application and the result will be like below.
Adding Banner Ads Programmatically Without XML
Lets create another Banner ad at the bottom of our view without using XML. All you need to do is creating & initializing banner ad , adding it to the specific layout, then loading the ad as below.
Code:
override fun onCreate(savedInstanceState: Bundle?) {
...
val adParam = AdParam.Builder().build();
val bannerView = BannerView(this);
// "testw6vs28auh3" is a dedicated test ad slot ID. To get real one, you need to have an enterprise level Huawei developer account.
bannerView.setAdId("testw6vs28auh3");
bannerView.setBannerAdSize(BannerAdSize.BANNER_SIZE_320_50);
val parentLayout = findViewById<ConstraintLayout>(R.id.clBannerMain);
val set = ConstraintSet();
// set view id, else getId() returns -1
bannerView.id = View.generateViewId()
parentLayout.addView(bannerView,0)
set.clone(parentLayout)
set.connect(bannerView.id, ConstraintSet.BOTTOM, parentLayout.id, ConstraintSet.BOTTOM, 0);
set.applyTo(parentLayout);
bannerView.loadAd(adParam)
...
}
When you run the code above you will see we have succesfully added a second banner ad to the bottom of the our view.
Code:
https://communityfile-dre.op.hicloud.com/FileServer/getFile/cmtybbs/023/106/056/0890090000023106056.20200827074704.78852832128128279354621703409783:50510914075520:2800:862740C17733B87A8CEAA65FD7B62221F9214A105D3414605B35C5EF96A0F1AE.png
Optional: Adding Ad Listener
After implementing banner ads to your project, if you want to proceed further, you can add Ad listener to listen ad events like AdLoaded is AdFailed is AdClicked etc. To do that, simply add an Ad Listener to your project like below
Code:
override fun onCreate(savedInstanceState: Bundle?) {
...
val adListener = object : AdListener() {
override fun onAdImpression() {
super.onAdImpression()
}
override fun onAdFailed(p0: Int) {
super.onAdFailed(p0)
}
override fun onAdLeave() {
super.onAdLeave()
}
override fun onAdClicked() {
super.onAdClicked()
}
override fun onAdClosed() {
super.onAdClosed()
}
override fun onAdOpened() {
super.onAdOpened()
}
override fun onAdLoaded() {
super.onAdLoaded()
}
}
//Add Ad Listener to which ad you want to listen.
bannerView.adListener = adListener
....
}
As you can see, it is really easy to implement banner ads to your android application with Huawei Ads Kit. Stay tuned for other ad types. You can find the github project below.
Resources
Disav0wed/Huawei_Banner_Ads_Demo:https://github.com/Disav0wed/Huawei_Banner_Ads_Demo
Official Huawei Documentation:https://developer.huawei.com/consumer/en/doc/development/HMS-Guides/ads-sdk-guide-banner
Codelab:https://developer.huawei.com/consumer/en/codelab/HUAWEIAdsSDK-BannerAds/index.html#2
Introduction
In this article, I would like to introduce the latest addition to Huawei Ads Kit, Roll Ads.
Roll Ads is an ads that will play before the video or stream content can be consumed by the user, this leads to a smooth User Experience and is a good source of revenue for App Developers.
I will also introduce Video Kit, a video player kit that enables developer to develop a video player or streaming services in few simple steps.
Implementing Roll Ads
Please ensure you have created your app on AGC Console, and setup the HMS Core Plugin.
You can follow the guide here.
Lets add the ads dependencies:
Code:
implementation 'com.huawei.hms:ads-lite:13.4.33.300'
Next, we can init the ads from our Application class:
Code:
override fun onCreate() {
super.onCreate()
// init HMS Ads Kit
HwAds.init(this)
}
Lets add our Instream Ads View on our activity xml:
Code:
<RelativeLayout
android:id="@+id/instream_ad_container"
android:layout_width="match_parent"
android:layout_height="200dp"
android:visibility="visible">
<!-- Roll ad view. -->
<com.huawei.hms.ads.instreamad.InstreamView
android:id="@+id/instream_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
To test our Ads, we can use the dedicated roll ads slot id: "testy3cglm3pj0"
Code:
val builder = InstreamAdLoader.Builder(this, "testy3cglm3pj0")
And we can set our ads as below
Code:
val adloader = builder.setTotalDuration(30)
.setMaxCount(1)
.setInstreamAdLoadListener(object : InstreamAdLoadListener {
override fun onAdFailed(p0: Int) {
}
override fun onAdLoaded(p0: MutableList<InstreamAd>?) {
instream_view.setInstreamAds(p0)
}
}).build()
adloader.loadAd(AdParam.Builder().build())
After setting up all this, you should be able to run the app and you will see a roll ads being played.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Implementing Video Kit
Now lets add Video Kit dependencies to our build.gradle
Code:
implementation "com.huawei.hms:videokit-player:1.0.1.300"
We can initialize our video kit (wise player) in Application class as well, like so:
First, let's add a reference for our wisePlayerFactory
Code:
companion object {
lateinit var wisePlayerFactory: WisePlayerFactory
}
We can initialize the object on Application Create:
Code:
private fun initPlayer() {
// DeviceId test is used in the demo, specific access to incoming deviceId after encryption
val factoryOptions = WisePlayerFactoryOptions.Builder().setDeviceId("test-device1").build()
WisePlayerFactory.initFactory(this, factoryOptions, initFactoryCallback)
}
override fun onCreate() {
super.onCreate()
HwAds.init(this)
initPlayer()
}
Lastly, we need create the callback and getter/setter for our wisePlayerFactory
Code:
private val initFactoryCallback: InitFactoryCallback = object : InitFactoryCallback {
override fun onSuccess(wisePlayerFactory: WisePlayerFactory) {
setWisePlayerFactory(wisePlayerFactory)
}
override fun onFailure(errorCode: Int, reason: String) {
}
}
fun getWisePlayerFactory(): WisePlayerFactory? {
return MyApplication.wisePlayerFactory
}
private fun setWisePlayerFactory(wisePlayerFactory: WisePlayerFactory) {
MyApplication.wisePlayerFactory = wisePlayerFactory
}
On our activity xml, we need to create SurfaceView to be attached to our WisePlayer
Code:
<FrameLayout
android:id="@+id/frame_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone">
<SurfaceView
android:id="@+id/surface_view"
android:layout_width="match_parent"
android:layout_height="200dp" />
</FrameLayout>
Combining the two
Now that we have both kits setup, lets combine them.
We will only start the video once the ads is finished displayed.
Let's add a listener to our Instream Ads so that we know once the ads is finished playing
Code:
instream_view.setInstreamMediaStateListener(object : InstreamMediaStateListener{
override fun onMediaPause(p0: Int) {
}
override fun onMediaProgress(p0: Int, p1: Int) {
}
override fun onMediaCompletion(p0: Int) {
// Initialize our video player
player = MyApplication.getWisePlayerFactory().createWisePlayer()
// video will be played once the video is ready to load the data
player.setReadyListener {
player.start()
}
player.setVideoType(0);
player.setBookmark(10000);
player.setCycleMode(1);
// set the video to play
player.setPlayUrl("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4")
player.setView(surface_view);
// initiate video loading
player.ready()
// hide the ads container, and show the video player
instream_ad_container.visibility = View.GONE
frame_layout.visibility = View.VISIBLE
}
override fun onMediaError(p0: Int, p1: Int, p2: Int) {
}
override fun onMediaStart(p0: Int) {
}
override fun onMediaStop(p0: Int) {
}
})
Once you combined the two, you will see the stream/video will be played after the ads finished loading:
Tips & Trick
Do ensure that your instream view and wise player view size is similar, to provide a much better viewing experience for the user.
You cann add a skip button on the Roll Ads that will be only enabled after a certain time (for example 5 secs) so that the user can jump to the content after 5 sec of ads.
Conclusion
From this article, I hope this will help you to understand how to integrate our Roll Ads as well as Video Kit.
As you can see, implementation is very straight forward, I hope you guys can give it a try.
Do left a comment if you have any suggestions/questions.
Thank you!
Reference
Roll Ads - https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/publisher-service-instream-0000001058253743
Video Kit - https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides-V5/init-player-0000001050199407-V5 and
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/basic-play-process-0000001050197362
After taking a stunning picture, the user may want to use it as their lock screen image, but even more so, to add text art to give the lock screen a flawless magazine cover effect.
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Fortunately, Image Kit makes this easy, by endowing your app with the smart layout service, which empowers users to create magazine-reminiscent lock screen images on a whim.
2. Scenario
The smart layout service provides apps with nine different text layout styles, which correspond to the text layouts commonly seen in images, and help users add typeset text to images. By arranging images and text in such a wide range of different styles, the service enables users to relive memorable life experiences in exhilarating new ways.
3. Key Steps and Code for Integration
Preparations
1. Configure the Huawei Maven repository address.
Open the build.gradle file in your Android Studio project.
Go to buildscript > repositories and allprojects > repositories, and add the Maven repository address for the HMS Core SDK.
Code:
<p style="line-height: 1.5em;">buildscript {
repositories{
...
maven {url 'http://developer.huawei.com/repo/'}
}
}
allprojects {
repositories {
…
maven { url 'http://developer.huawei.com/repo/'}
}
}
</p>
2. Add the build dependencies for the HMS Core SDK.
Open the build.gradle file in the app directory of your project.
Add build dependencies in the dependencies section and use the Full-SDK of Scene Kit and AR Engine SDK.
Code:
<p style="line-height: 1.5em;">dependencies {
….
implementation "com.huawei.hms:image-vision:1.0.3.301"
implementation "com.huawei.hms:image-vision-fallback:1.0.3.301"
}
</p>
3. Add permissions in the AndroidManifest.xml file.
Open the AndroidManifest.xml file in the main directory, and add the relevant permissions above the <application line.
Code:
<p style="line-height: 1.5em;"><!—Permissions to access Internet, and read data from and write data to the external storage-->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</p>
Development Procedure
1. Layout
The following parameters need to be configured to facilitate smart layout display:
1. title: copywriting title, which is mandatory and can contain a maximum of 10 characters. If the title exceeds 10 characters, extra characters will be forcibly truncated.
2. description: copywriting content, which can contain a maximum of 66 characters. If the content exceeds 66 characters, extra characters will be forcibly truncated and replaced with an ellipsis (...).
3. copyRight: name of the copyright holder, which can contain a maximum of 10 characters. If the name exceeds 10 characters, extra characters will be forcibly truncated and replaced with an ellipsis (...).
4. anchor: link that redirects users to the details, which can contain a maximum of 6 characters. If the link exceeds 6 characters, extra characters will be forcibly truncated and replaced with an ellipsis (...).
5. info: copywriting layout style. You can select one from info1 to info9. info8 represents a vertical layout, which currently applies only to Chinese text. info3 is used by default if the user selects info8 but the input title and text are not in Chinese.
Functions of certain buttons:
INIT_SERVICE: Initializes the service.
SOTP_SERVICE: Stops the service.
IMAGE: Opens an image on the mobile phone.
GET_RESULT: Obtains the typeset image to be displayed.
2. INIT_SERVICE: Initializing the Service
To call setVisionCallBack during service initialization, your app must implement the ImageVision.VisionCallBack API and override its onSuccess(int successCode) and onFailure(int errorCode) methods. The onSuccess method is called after successful framework initialization. In the onSuccess method, the smart layout service will be initialized again.
Code:
private void initTag(final Context context) {
// Obtain an ImageVisionImpl object.
imageVisionTagAPI = ImageVision.getInstance(this);
imageVisionTagAPI.setVisionCallBack(new ImageVision.VisionCallBack() {
@Override
public void onSuccess(int successCode) {
int initCode = imageVisionTagAPI.init(context, authJson);
}
@Override
public void onFailure(int errorCode) {
LogsUtil.e(TAG, "getImageVisionAPI failure, errorCode = " + errorCode);
}
});
}
For more details about the format of authJson, please visit Filter Service.
The token is mandatory. For more details about how to obtain a token, please visit How to Obtain a Token.
Code:
/**
* Gets token.
*
* @param context the context
* @param client_id the client id
* @param client_secret the client secret
* @return the token
*/
public static String getToken(Context context, String client_id, String client_secret) {
String token = "";
try {
String body = "grant_type=client_credentials&client_id=" + client_id + "&client_secret=" + client_secret;
token = commonHttpsRequest(context, body, context.getResources().getString(R.string.urlToken));
if (token != null && token.contains(" ")) {
token = token.replaceAll(" ", "+");
token = URLEncoder.encode(token, "UTF-8");
}
} catch (UnsupportedEncodingException e) {
LogsUtil.e(TAG, e.getMessage());
}
return token;
}
For more, you can check https://forums.developer.huawei.com/forumPortal/en/topic/0201465106068040043
Overview
In this article, I will create a Doctor Consult android application in which I will integrate HMS Core kits such as Huawei ID, Crash and Analytics.
Huawei ID Service Introduction
Huawei ID login provides you with simple, secure, and quick sign-in and authorization functions. Instead of entering accounts and passwords and waiting for authentication, users can just tap the Sign in with HUAWEI ID button to quickly and securely sign in to your app with their HUAWEI IDs.
Prerequisite
Huawei Phone EMUI 3.0 or later.
Non-Huawei phones Android 4.4 or later (API level 19 or higher).
HMS Core APK 4.0.0.300 or later
Android Studio
AppGallery Account.
App Gallery Integration process
Sign In and Create or Choose a project on AppGallery Connect portal.
Navigate to Project settings and download the configuration file.
Navigate to General Information, and then provide Data Storage location.
App Development
Create A New Project.
Configure Project Gradle.
Code:
buildscript {
repositories {
google()
jcenter()
maven { url 'https://developer.huawei.com/repo/' }
}
dependencies {
classpath "com.android.tools.build:gradle:4.0.1"
classpath 'com.google.gms:google-services:4.3.5'
classpath 'com.huawei.agconnect:agcp:1.3.1.300'
}
}
allprojects {
repositories {
google()
jcenter()
maven { url 'https://developer.huawei.com/repo/' }
}
}
task clean(type: Delete) {
Configure App Gradle.
Code:
api 'com.huawei.hms:dynamicability:1.0.11.302'
implementation 'com.huawei.agconnect:agconnect-auth:1.4.1.300'
implementation 'com.huawei.hms:hwid:5.3.0.302'
implementation 'com.huawei.hms:ads-lite:13.4.30.307'
implementation 'com.huawei.agconnect:agconnect-remoteconfig:1.6.0.300'
implementation 'com.huawei.hms:hianalytics:5.0.3.300'
implementation 'com.huawei.agconnect:agconnect-crash:1.4.1.300'
Configure AndroidManifest.xml.
Code:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Create Activity class with XML UI.
MainActivity:
Code:
public class MainActivity extends AppCompatActivity {
Toolbar t;
DrawerLayout drawer;
EditText nametext;
EditText agetext;
ImageView enter;
RadioButton male;
RadioButton female;
RadioGroup rg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawer = findViewById(R.id.draw_activity);
t = (Toolbar) findViewById(R.id.toolbar);
nametext = findViewById(R.id.nametext);
agetext = findViewById(R.id.agetext);
enter = findViewById(R.id.imageView7);
male = findViewById(R.id.male);
female = findViewById(R.id.female);
rg=findViewById(R.id.rg1);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, t, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView nav = findViewById(R.id.nav_view);
enter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name = nametext.getText().toString();
String age = agetext.getText().toString();
String gender= new String();
int id=rg.getCheckedRadioButtonId();
switch(id)
{
case R.id.male:
gender = "Mr.";
break;
case R.id.female:
gender = "Ms.";
break;
}
Intent symp = new Intent(MainActivity.this, SymptomsActivity.class);
symp.putExtra("name",name);
symp.putExtra("gender",gender);
startActivity(symp);
}
});
nav.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch(menuItem.getItemId())
{
case R.id.nav_sos:
Intent in = new Intent(MainActivity.this, call.class);
startActivity(in);
break;
case R.id.nav_share:
Intent myIntent = new Intent(Intent.ACTION_SEND);
myIntent.setType("text/plain");
startActivity(Intent.createChooser(myIntent,"SHARE USING"));
break;
case R.id.nav_hosp:
Intent browserIntent = new Intent(Intent.ACTION_VIEW);
browserIntent.setData(Uri.parse("https://www.google.com/maps/search/hospitals+near+me"));
startActivity(browserIntent);
break;
case R.id.nav_cntus:
Intent c_us = new Intent(MainActivity.this, activity_contact_us.class);
startActivity(c_us);
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
}
}
App Build Result
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Tips and Tricks
Identity Kit displays the HUAWEI ID registration or sign-in page first. You can use the functions provided by Identity Kit only after signing in using a registered HUAWEI ID.
Conclusion
In this article, we have learned how to integrate Huawei ID in Android application. After completely read this article user can easily implement Huawei ID in the Doctor Consult application.
Thanks for reading this article. Be sure to like and comment to this article, if you found it helpful. It means a lot to me.
References
HMS Docs:
https://developer.huawei.com/consum.../HMSCore-Guides/introduction-0000001050048870