Find the introduction Sliders and Huawei Account Kit Integration in Money Management Android app (Kotlin) - Part 1 - Huawei Developers

{
"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"
}
Introduction
In this article, we can learn how to integrate the Huawei Account Kit in Money Management app along with introduction slides. The sliders will provide the quick view of the app functionalities. So, I will provide the series of articles on this Money Management App, in upcoming articles I will integrate other Huawei Kits.
Account Kit
Huawei Account Kit provides for developers with simple, secure, and quick sign-in and authorization functions. User is not required to enter accounts, passwords and waiting for authorization. User can click on Sign In with HUAWEI ID button to quickly and securely sign in to the app.
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. Click Manage APIs tab and enable Account Kit.
9. Add the below maven URL in build.gradle(Project) file under the repositories of buildscript, dependencies and allprojects, refer Add Configuration.
Java:
maven { url 'http://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.6.0.300'
10. Add the below plugin and dependencies in build.gradle(Module) file.
Java:
apply plugin: id 'com.huawei.agconnect'
// Huawei AGC
implementation 'com.huawei.agconnect:agconnect-core:1.6.0.300'
// Huawei Account Kit
implementation 'com.huawei.hms:hwid:6.3.0.301'
11. Now Sync the gradle.
12. Add the required permission to the AndroidManifest.xml file.
Java:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
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 Huawei login button and also introduction slides.
Java:
class MainActivity : AppCompatActivity() {
private var viewPager: ViewPager? = null
private var viewPagerAdapter: ViewPagerAdapter? = null
private lateinit var dots: Array<TextView?>
private var dotsLayout: LinearLayout? = null
companion object {
private lateinit var layouts: IntArray
}
// Account Kit variables
private var mAuthManager: AccountAuthService? = null
private var mAuthParam: AccountAuthParams? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewPager = findViewById(R.id.view_pager)
dotsLayout= findViewById(R.id.layoutDots)
// Introduction slides, create xml files under "app > res > layout"
layouts = intArrayOf(R.layout.slider_1, R.layout.slider_2, R.layout.slider_3,R.layout.slider_4)
addBottomDots(0)
// Making notification bar transparent
changeStatusBarColor()
viewPagerAdapter = ViewPagerAdapter()
viewPager!!.adapter = viewPagerAdapter
viewPager!!.addOnPageChangeListener(viewListener)
// For the next and previous buttons
btn_skip.setOnClickListener { view ->
val intent = Intent([email protected], Home::class.java)
startActivity(intent)
finish()
}
btn_next.setOnClickListener { view ->
val current: Int = getItem(+1)
if (current < layouts.size) {
// Move to another slide
viewPager!!.currentItem = current
} else {
val i = Intent([email protected], Home::class.java)
startActivity(i)
finish()
}
}
// Account kit button click Listener
btn_login.setOnClickListener(mOnClickListener)
}
// Dots functionality
private fun addBottomDots(position: Int) {
dots = arrayOfNulls(layouts!!.size)
val colorActive = resources.getIntArray(R.array.dot_active)
val colorInactive = resources.getIntArray(R.array.dot_inactive)
dotsLayout!!.removeAllViews()
for (i in dots.indices) {
dots!![i] = TextView(this)
dots[i]!!.text = Html.fromHtml("•")
dots[i]!!.textSize = 35f
dots[i]!!.setTextColor(colorInactive[position])
dotsLayout!!.addView(dots[i])
}
if (dots.size > 0) dots[position]!!.setTextColor(colorActive[position])
}
private fun getItem(i: Int): Int {
return viewPager!!.currentItem + i
}
// Viewpager change Listener
private var viewListener: OnPageChangeListener = object : OnPageChangeListener {
override fun onPageSelected(position: Int) {
addBottomDots(position)
// changing the next button text 'NEXT''
if (position == layouts!!.size - 1) {
btn_next.text = "Proceed "
btn_skip.visibility = View.GONE
} else {
btn_next.text = "Next "
btn_skip.visibility = View.VISIBLE
}
}
override fun onPageScrollStateChanged(state: Int) {}
override fun onPageScrolled( position: Int, positionOffset: Float, positionOffsetPixels: Int) {
}
}
// Making notification bar transparent
private fun changeStatusBarColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val window = window
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.statusBarColor = Color.TRANSPARENT
}
}
// PagerAdapter class which will inflate our sliders in our ViewPager
inner class ViewPagerAdapter : PagerAdapter() {
private var layoutInflater: LayoutInflater? = null
override fun instantiateItem(myContainer: ViewGroup, mPosition: Int): Any {
layoutInflater = getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater?
val v: View = layoutInflater!!.inflate(layouts[mPosition], myContainer, false)
myContainer.addView(v)
return v
}
override fun getCount(): Int {
return layouts.size
}
override fun isViewFromObject(mView: View, mObject: Any): Boolean {
return mView === mObject
}
override fun destroyItem(mContainer: ViewGroup, mPosition: Int, mObject: Any) {
val v = mObject as View
mContainer.removeView(v)
}
}
// Account kit, method to send an authorization request.
private fun signIn() {
mAuthParam = AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM)
.setIdToken()
.setAccessToken()
.setProfile()
.createParams()
mAuthManager = AccountAuthManager.getService([email protected], mAuthParam)
startActivityForResult(mAuthManager?.signInIntent, 1002)
}
private val mOnClickListener: View.OnClickListener = object : View.OnClickListener {
override fun onClick(v: View?) {
when (v?.id) {
R.id.btn_login -> signIn()
}
}
}
// Process the authorization result.
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 1002 ) {
val authAccountTask = AccountAuthManager.parseAuthResultFromIntent(data)
if (authAccountTask.isSuccessful) {
Toast.makeText(this, "SigIn success", Toast.LENGTH_LONG).show()
val intent = Intent([email protected], Home::class.java)
startActivity(intent)
} else {
Toast.makeText(this, "SignIn failed: " + (authAccountTask.exception as ApiException).statusCode, Toast.LENGTH_LONG).show()
}
}
}
}
In the activity_main.xml we can create the UI screen for Huawei image button and slides operating buttons.
Java:
<?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">
<androidx.viewpager.widget.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="500dp" />
<LinearLayout
android:id="@+id/layoutDots"
android:layout_width="match_parent"
android:layout_height="35dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="132dp"
android:gravity="center"
android:orientation="horizontal">
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="3dp"
android:alpha=".5"
android:layout_above="@id/layoutDots"
android:background="@android:color/white" />
<Button
android:id="@+id/btn_next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:padding="5dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="85dp"
android:background="@null"
android:textSize="16sp"
android:text="Next"
android:textAllCaps="false"
android:textColor="@color/dot_dark_screen3" />
<Button
android:id="@+id/btn_skip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="85dp"
android:layout_marginLeft="10dp"
android:textSize="16sp"
android:background="@null"
android:textAllCaps="false"
android:text="Skip"
android:textColor="@color/dot_dark_screen3" />
<ImageView
android:id="@+id/btn_login"
android:layout_width="90dp"
android:layout_height="70dp"
android:layout_alignBottom="@id/btn_next"
android:layout_centerHorizontal="true"
android:layout_marginBottom="-83dp"
android:padding="5dp"
android:text="Sign In"
android:textAllCaps="false"
android:textColor="@color/dot_dark_screen1"
app:srcCompat="@drawable/hwid_auth_button_round_black" />
</RelativeLayout>
Create slider_1.xml and placed under layout folder for the slides view and also add the content image in drawable folder. Repeat the same process for another 3 slides also.
Java:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="600dp"
android:background="@drawable/slide_1">
</androidx.constraintlayout.widget.ConstraintLayout>
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 Account Kit in Money Management app along with introduction slides. The sliders will provide the quick view of the app functionalities. So, I will provide the series of articles on this Money Management 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
Account Kit – Documentation
Account Kit – Training Video

Related

Capture the forms using Form Recognition feature by Huawei ML Kit in Android (Kotlin)

{
"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"
}
Introduction
In this article, we can learn how to integrate Form Recognition feature using Huawei ML Kit.
Form Recognition service can recognize the information from Form and it will return table content such as table count, rows, columns, cell coordinate, text Information etc. form text in Chinese and English (including punctuation) from input images.
This service is majorly used in daily work scenarios. For example, suppose if you want to covert large number of paper questionnaires into electronic documents, this service reduces manual input costs and greatly improves work efficiency.
Precautions
1. Forms such as questionnaires can be recognized.
2. Currently images containing multiple forms cannot be recognized.
3. Shooting Angle: The horizontal tilt angle is less than 5 degrees.
4. Form Integrity: No missing corners and no bent or segment lines.
5. Form Content: Only printed content can be recognized, images, hand written content, seals and watermarks in the form cannot be recognized.
6. Image Specification: Image ratio should be less than or equal 3:1, resolution must be greater than 960 x 960 px.
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 21 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. Click Manage APIs tab and enable ML Kit.
9. Add the below maven URL in build.gradle(Project) file under the repositories of buildscript, dependencies and allprojects, refer Add Configuration.
Java:
maven { url 'http://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
10. Add the below plugin and dependencies in build.gradle(Module) file.
Java:
apply plugin: 'com.huawei.agconnect'
// Huawei AGC
implementation 'com.huawei.agconnect:agconnect-core:1.5.0.300'
// ML Kit base SDK
implementation 'com.huawei.hms:ml-computer-vision-formrecognition:3.2.0.300'
// ML Kit Form Recognition model package
implementation 'com.huawei.hms:ml-computer-vision-formrecognition-model:3.2.0.300'
11. Now Sync the gradle.
12. Add the required permission to the AndroidManifest.xml file.
Java:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
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.
Java:
class MainActivity : AppCompatActivity() {
private var setting: MLFormRecognitionAnalyzerSetting? = null
private var analyzer: MLFormRecognitionAnalyzer? = null
private var mImageView: ImageView? = null
private var text: TextView? = null
private var textTotal:TextView? = null
private var mlFrame: MLFrame? = null
private var imageUri: Uri? = null
private var bitmap: Bitmap? = null
private val camRequestCode = 100
private val storageRequestCode = 200
private val sum = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mImageView = findViewById<View>(R.id.image) as ImageView?
text = findViewById(R.id.text)
textTotal = findViewById(R.id.text_total)
setting = MLFormRecognitionAnalyzerSetting.Factory().create()
analyzer = MLFormRecognitionAnalyzerFactory.getInstance().getFormRecognitionAnalyzer(setting)
}
fun onLoadImage(view: View?) {
val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
startActivityForResult(intent, storageRequestCode)
}
fun onClikCam(view: View?) {
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.CAMERA), camRequestCode)
} else {
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(intent, camRequestCode)
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String?>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == camRequestCode) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(intent, camRequestCode)
} else {
Toast.makeText(this, "Camera permission denied", Toast.LENGTH_LONG).show()
}
}
if (requestCode == storageRequestCode) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
startActivityForResult(intent, storageRequestCode)
} else {
Toast.makeText(this, "Storage permission denied", Toast.LENGTH_LONG).show()
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode === RESULT_OK && requestCode === storageRequestCode) {
imageUri = data!!.data
try {
bitmap = MediaStore.Images.Media.getBitmap(this.contentResolver, imageUri)
mImageView!!.setImageBitmap(bitmap)
callFormService()
} catch (e: IOException) {
e.printStackTrace()
}
} else if (resultCode === RESULT_OK && requestCode === camRequestCode) {
bitmap = data!!.extras!!.get("data") as Bitmap?
mImageView!!.setImageBitmap(bitmap)
callFormService()
}
}
private fun callFormService() {
mlFrame = MLFrame.fromBitmap(bitmap)
analyzer = MLFormRecognitionAnalyzerFactory.getInstance().formRecognitionAnalyzer
val task: Task<JsonObject> = analyzer!!.asyncAnalyseFrame(mlFrame)
task.addOnSuccessListener(OnSuccessListener<JsonObject?> { jsonObject ->
if (jsonObject != null && jsonObject["retCode"].asInt == MLFormRecognitionConstant.SUCCESS) {
val gson = Gson()
val result = jsonObject.toString()
val mlObject = gson.fromJson(result, MLFormRecognitionTablesAttribute::class.java)
val tableAttributeArrayList = mlObject.tablesContent.tableAttributes
val tableCellAttributes = tableAttributeArrayList[0].tableCellAttributes
for (attribute in tableCellAttributes) {
val info = attribute.textInfo
text!!.text = """
${text!!.text}
$info
""".trimIndent()
}
Toast.makeText([email protected],"Successfully Form Recognized",Toast.LENGTH_LONG).show()
Log.d("TAG", "result: $result")
} else if (jsonObject != null && jsonObject["retCode"].asInt == MLFormRecognitionConstant.FAILED) {
Toast.makeText([email protected], "Form Recognition Convertion Failed", Toast.LENGTH_LONG).show()
}
textTotal!!.text = "Total Cart Value : $sum Rs "
}).addOnFailureListener(OnFailureListener {
Toast.makeText([email protected],"Form Recognition API Failed", Toast.LENGTH_LONG).show()
})
}
}
In the activity_main.xml we can create the UI screen.
Java:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".MainActivity">
<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_marginTop="?actionBarSize" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:orientation="horizontal">
<ImageButton
android:id="@+id/btn_storage1"
android:layout_width="85dp"
android:layout_height="70dp"
android:layout_marginLeft="30dp"
android:layout_alignParentTop="true"
android:layout_marginBottom="10dp"
android:paddingTop="10dp"
android:onClick="onLoadImage"
android:layout_centerHorizontal="true"
android:src="@drawable/gall" />
<ImageButton
android:id="@+id/btn_capture1"
android:layout_width="85dp"
android:layout_height="70dp"
android:onClick="onClikCam"
android:layout_marginLeft="100dp"
android:layout_marginRight="30dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:paddingBottom="10dp"
android:src="@drawable/cam" />
</LinearLayout>
<TextView
android:id="@+id/text_total"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:textSize="17sp"
android:textColor="@android:color/holo_red_dark"
android:textStyle="bold" />
<ScrollView
android:layout_marginTop="8dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:textSize="17sp"
android:textColor="@android:color/holo_red_dark"
android:textStyle="bold" />
</ScrollView>
</LinearLayout>
Demo
Tips and Tricks
1. Make sure you are already registered as Huawei developer.
2. Set minSDK version to 21 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 learnet how to integrate Form Recognition feature using Huawei ML Kit.
Form Recognition service can recognize the information from Form and it will return table content such as table count, rows, columns, cell coordinate, text Information etc. form text in Chinese and English (including punctuation) from input images.
I hope you have read this article. If you found it is helpful, please provide likes and comments.
Reference
ML Kit - Form Recognition
ML kIT - Training Video

Find the RecyclerView Item Click Listeners to Navigate to Different activities in Quiz Android app (Kotlin) – Part 4

{
"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"
}
Introduction
In this article, we can learn how to click the items of Recyclerview to navigate to different activities in Quiz App. Here, I have given the items in grid view to click each item. So, I will provide a series of articles on this Quiz App, in upcoming articles.
If you are new to this application, follow my previous articles.
https://forums.developer.huawei.com/forumPortal/en/topic/0202877278014350004
https://forums.developer.huawei.com/forumPortal/en/topic/0201884103719030016?fid=0101187876626530001
https://forums.developer.huawei.com/forumPortal/en/topic/0202890333711770040
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 on the 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.
Java:
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.
Java:
apply plugin: id 'com.huawei.agconnect'
// Huawei AGC
implementation 'com.huawei.agconnect:agconnect-core:1.6.0.300'
// Recyclerview
implementation 'androidx.recyclerview:recyclerview:1.2.1'
// Lifecycle components
implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"
10. Now Sync the gradle.
Let us move to development
I have created a project on Android studio with empty activity let us start coding.
In the Home.kt we can find the business logic for button click listeners.
Java:
class Home : AppCompatActivity(), HomeAdapter.ItemListener {
private lateinit var recyclerView: RecyclerView
private lateinit var arrayList: ArrayList<QuesIcons>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
recyclerView = findViewById(R.id.recyclerview_list)
arrayList = ArrayList()
arrayList.add(QuesIcons("Android", R.drawable.android_icon, "#09A9FF"))
arrayList.add(QuesIcons("HMS", R.drawable.huawei_icon, "#3E51B1"))
arrayList.add(QuesIcons("Sports", R.drawable.sports_icon, "#673BB7"))
arrayList.add(QuesIcons("Country Flags", R.drawable.flags_icon, "#4BAA50"))
val adapter = HomeAdapter(applicationContext, arrayList, this)
recyclerView.adapter = adapter
recyclerView.layoutManager = GridLayoutManager(this, 2)
recyclerView.setHasFixedSize(true)
}
override fun onItemClick(item: Int) {
when(item ) {
0 -> {val intent = Intent([email protected], AndroidActivity::class.java)
startActivity(intent)
}
1 -> {val intent = Intent([email protected], HMSActivity::class.java)
startActivity(intent)
}
2 -> {val intent = Intent([email protected], SportsActivity::class.java)
startActivity(intent)
}
3 -> {val intent = Intent([email protected], QuizActivity::class.java)
startActivity(intent)
}
}
}
}
In the HomeAdapter.kt we can find the business logic to holder the adapter items.
Java:
class HomeAdapter(private val mContext: Context, private val mValues: ArrayList<QuesIcons>, private var mListener: ItemListener?) :
RecyclerView.Adapter<HomeAdapter.ViewHolder>() {
inner class ViewHolder(v: View) : RecyclerView.ViewHolder(v), View.OnClickListener {
private val textView: TextView
private val imageView: ImageView
private val relativeLayout: RelativeLayout
private var item: QuesIcons? = null
fun setData(item: QuesIcons) {
this.item = item
textView.text = item.heading
imageView.setImageResource(item.titleImage)
relativeLayout.setBackgroundColor(Color.parseColor(item.colour))
}
override fun onClick(view: View) {
if (mListener != null) {
item?.let { mListener!!.onItemClick(adapterPosition) }
}
}
init {
v.setOnClickListener(this)
textView = v.findViewById<View>(R.id.text_item) as TextView
imageView = v.findViewById<View>(R.id.img_icon) as ImageView
relativeLayout = v.findViewById<View>(R.id.relativeLayout) as RelativeLayout
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view: View = LayoutInflater.from(mContext).inflate(R.layout.home_list, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {
viewHolder.setData(mValues[position])
}
override fun getItemCount(): Int {
return mValues.size
}
interface ItemListener {
fun onItemClick(position: Int)
}
}
Create QuesIcons.kt data class to find the declared the data.
Java:
data class QuesIcons(var heading: String, var titleImage: Int, var colour: String)
In the activity_home.xml we can create the recycler view list.
Java:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
android:paddingLeft="8dp"
android:paddingRight="8dp"
tools:context=".Home">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerview_list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
In the home_list.xml we can create customize view for items.
Java:
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/cardView"
android:layout_width="match_parent"
android:layout_height="170dp"
android:layout_margin="4dp"
card_view:cardCornerRadius="4dp">
<RelativeLayout
android:id="@+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginTop="10dp"
android:layout_gravity="center">
<ImageView
android:id="@+id/img_icon"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_centerInParent="true"
android:contentDescription="@null"
card_view:tint="@color/white" />
<TextView
android:id="@+id/text_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textColor="@android:color/white"
android:textSize="16sp"
android:layout_below="@+id/img_icon" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
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 click the items of Recyclerview to navigate to different activities in Quiz App. Here, we can find the items in grid view to click each item. So, I will provide a series of articles on this Quiz App, in upcoming articles. So, I will provide a series of articles on this Quiz App, in upcoming articles.
I hope you have read this article. If you found it helpful, please provide likes and comments.
Reference
Clik here - https://www.geeksforgeeks.org/android-recyclerview/

Search the hospitals using Huawei Map Kit, Site Kit and Location Kit in Patient Tracking Android app (Kotlin) – Part 5

{
"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"
}
Introduction
In this article, we can learn how to search the hospitals located by source and destination address with HMS Core Kits such as Map, Site, and Location Kits. Map kit is to display maps, it covers map data of more than 200 countries and regions for searching any location address. Location kit provides to get the current location and location updates, and it provides flexible location based services globally to the users. Site kit provides with convenient and secure access to diverse, place-related services to users.
So, I will provide a series of articles on this Patient Tracking App, in upcoming articles I will integrate other Huawei Kits.
If you are new to this application, follow my previous articles.
https://forums.developer.huawei.com/forumPortal/en/topic/0201902220661040078
https://forums.developer.huawei.com/forumPortal/en/topic/0201908355251870119
https://forums.developer.huawei.com/forumPortal/en/topic/0202914346246890032
https://forums.developer.huawei.com/forumPortal/en/topic/0202920411340450018
Map Kit
Map Kit covers map data of more than 200 countries and regions, and supports over 70 languages. User can easily integrate map-based functions into your apps using SDK. It optimizes and enriches the map detail display capability. Map Kit supports gestures including zoom, rotation, moving and tilt gestures to ensure smooth interaction experience.
Location Kit
Location Kit combines the GPS, Wi-Fi and base station location functionalities in your app to build up global positioning capabilities, allows to provide flexible location-based services targeted at users around globally. Currently, it provides three main capabilities: fused location, activity identification and geo-fence. You can call one or more of these capabilities as required.
Site Kit
Site Kit provides the place related services for apps. It provides that to search places with keywords, find nearby place, place suggestion for user search, and find the place details using the unique id.
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. Click Manage APIs tab and enable Map Kit, Site Kit and Location Kit.
9. Add the below maven URL in build.gradle(Project) file under the repositories of buildscript, dependencies and allprojects, refer Add Configuration.
Java:
maven { url 'http://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.6.0.300'
10. Add the below plugin and dependencies in build.gradle(Module) file.
Java:
apply plugin: 'com.huawei.agconnect'
// Huawei AGC
implementation 'com.huawei.agconnect:agconnect-core:1.6.0.300'
// Huawei Map
implementation 'com.huawei.hms:maps:6.2.0.301'
// Huawei Site Kit
implementation 'com.huawei.hms:site:6.2.0.301'
// Huawei Location Kit
implementation 'com.huawei.hms:location:6.2.0.300'
11. Now Sync the gradle.
12. Add the required permission to the AndroidManifest.xml file.
Java:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="com.huawei.appmarket.service.commondata.permission.GET_COMMON_DATA"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
// To obtain the coarse longitude and latitude of a user with Wi-Fi network or base station.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
// To receive location information from satellites through the GPS chip.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
Let us move to development
I have created a project on Android studio with empty activity let us start coding.
In the SearchActivity.kt we can find the business logic.
Java:
class SearchActivity : AppCompatActivity(), OnMapReadyCallback, View.OnClickListener {
private lateinit var hmap: HuaweiMap
private lateinit var mMapView: MapView
private var mMarker: Marker? = null
private var mCircle: Circle? = null
private var isSourceAddressField: Boolean = false
private var pickupLat: Double = 0.0
private var pickupLng: Double = 0.0
private var dropLat: Double = 0.0
private var dropLng: Double = 0.0
private var searchService: SearchService? = null
private var searchIntent: SearchIntent? = null
private lateinit var mFusedLocationProviderClient: FusedLocationProviderClient
companion object {
private const val TAG = "MapViewDemoActivity"
private const val MAPVIEW_BUNDLE_KEY = "MapViewBundleKey"
private val LAT_LNG = LatLng(12.9716, 77.5946)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_search)
// Get mapView
mMapView = findViewById(R.id.mapView)
var mapViewBundle: Bundle? = null
if (savedInstanceState != null) {
mapViewBundle = savedInstanceState.getBundle(MAPVIEW_BUNDLE_KEY)
}
// Add "Your API key" in api_key field value
MapsInitializer.setApiKey("DAEDADRgIFzXbAJpOqImvjRAGRkmm3wGTux0O6JBiaddIPMNTJ4SawIN8ZHWu28dtc1f1H3Cqzh0LC1cgYIvBnl1edWVuWkjciH4NA==")
mMapView.onCreate(mapViewBundle)
// get map by async method
mMapView.getMapAsync(this)
//Checking permission
checkLocationPermission()
// Location service
mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
//Initialize Search Service
getLocationFromService()
//Initialize OnClickListener
customCurrentLocation.setOnClickListener(this)
pickUpLocation.setOnClickListener(this)
dropLocation.setOnClickListener(this)
}
override fun onMapReady(map: HuaweiMap?) {
Log.d(TAG, "onMapReady: ")
// Get the HuaweiMap instance in this call back method.
hmap = map!!
// Move camera by CameraPosition param, latlag and zoom params can set here.
val build = CameraPosition.Builder().target(LatLng(13.0827, 80.2707)).zoom(10f).build()
val cameraUpdate = CameraUpdateFactory.newCameraPosition(build)
hmap.animateCamera(cameraUpdate)
hmap.setMaxZoomPreference(10f)
hmap.setMinZoomPreference(1f)
// Marker can be add by HuaweiMap
mMarker = hmap.addMarker(
MarkerOptions().position(LAT_LNG)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.garden_icon))
.clusterable(true))
mMarker?.showInfoWindow()
// circle can be add by HuaweiMap
mCircle = hmap.addCircle(
CircleOptions().center(LatLng(28.7041, 77.1025)).radius(45000.0).fillColor(Color.GREEN))
mCircle?.fillColor = Color.TRANSPARENT
}
override fun onStart() {
super.onStart()
mMapView.onStart()
}
override fun onStop() {
super.onStop()
mMapView.onStop()
}
override fun onDestroy() {
super.onDestroy()
mMapView.onDestroy()
}
override fun onPause() {
mMapView.onPause()
super.onPause()
}
override fun onResume() {
super.onResume()
mMapView.onResume()
}
private fun checkLocationPermission() {
// check location permission
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
if (ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
val strings = arrayOf(ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION)
ActivityCompat.requestPermissions(this, strings, 1)
}
} else {
if (ActivityCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this,ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this,"android.permission.ACCESS_BACKGROUND_LOCATION") != PackageManager.PERMISSION_GRANTED) {
val strings = arrayOf(ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION,
"android.permission.ACCESS_BACKGROUND_LOCATION")
ActivityCompat.requestPermissions(this, strings, 2)
}
}
}
private fun getLocationFromService() {
// Add your API Key in encode
searchService = SearchServiceFactory.create(this,
URLEncoder.encode("Add your api_key"))
}
override fun onClick(v: View?) {
val id = v?.id
if (id == R.id.pickUpLocation) {
locationBox(100)
} else if (id == R.id.dropLocation) {
locationBox(101)
} else if (id == R.id.customCurrentLocation) {
getLastLocation()
}
}
private fun locationBox(requestcode: Int) {
searchIntent = SearchIntent()
searchIntent!!.setApiKey(URLEncoder.encode("DAEDADRgIFzXbAJpOqImvjRAGRkmm3wGTux0O6JBiaddIPMNTJ4SawIN8ZHWu28dtc1f1H3Cqzh0LC1cgYIvBnl1edWVuWkjciH4NA==", "utf-8"))
val intent = searchIntent!!.getIntent(this)
startActivityForResult(intent, requestcode)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, @Nullable data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 100) {
if (SearchIntent.isSuccess(resultCode)) {
isSourceAddressField = true
val site: Site = searchIntent!!.getSiteFromIntent(data)
pickUpLocation.setText(site.name)
querySuggestion()
}
}
if (requestCode == 101) {
if (SearchIntent.isSuccess(resultCode)) {
isSourceAddressField = false
val site: Site = searchIntent!!.getSiteFromIntent(data)
dropLocation.setText(site.name)
querySuggestion()
}
}
}
private fun querySuggestion() {
val request = QuerySuggestionRequest()
val query: String?
if (isSourceAddressField) {
query = pickUpLocation?.text.toString()
}else{
query = dropLocation?.text.toString()
}
if (!TextUtils.isEmpty(query)) {
request.query = query
}
searchService?.querySuggestion(
request,
searchResultListener as SearchResultListener<QuerySuggestionResponse>?
)
}
private var searchResultListener =
object : SearchResultListener<QuerySuggestionResponse> {
override fun onSearchResult(results: QuerySuggestionResponse?) {
val stringBuilder = StringBuilder()
results?.let {
val sites = results.sites
if (sites != null && sites.size > 0) {
for (site in sites) {
val location = site.location
if (isSourceAddressField) {
pickupLat = location.lat
pickupLng = location.lng
moveCamera(LatLng(pickupLat, pickupLng))
} else {
dropLat = location.lat
dropLng = location.lng
moveCamera(LatLng(dropLat, dropLng))
}
break
}
} else {
stringBuilder.append("0 results")
}
}
}
override fun onSearchError(status: SearchStatus) {
}
}
private fun getLastLocation() {
try {
val lastLocation = mFusedLocationProviderClient.lastLocation
lastLocation.addOnSuccessListener(OnSuccessListener { location ->
if (location == null) {
[email protected]
}
moveCamera(LatLng(location.latitude, location.longitude))
[email protected]
}).addOnFailureListener { e ->
}
} catch (e: Exception) {
}
}
private fun moveCamera(latLng: LatLng) {
hmap!!.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15f))
}
}
In the activity_search.xml we can create the UI screen.
Java:
<?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"
android:orientation="vertical"
tools:context=".search.SearchActivity">
<com.huawei.hms.maps.MapView
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</com.huawei.hms.maps.MapView>
<RelativeLayout
android:id="@+id/startpoint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="42dp"
android:layout_marginTop="42dp"
android:layout_marginRight="62dp"
android:background="@drawable/blue_border_rounded_cornwe">
<EditText
android:id="@+id/pickUpLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/start_loc"
android:background="@android:color/transparent"
android:hint="Choose starting point "
android:maxLines="1"
android:paddingLeft="17dp"
android:paddingTop="15dp"
android:paddingBottom="15dp"
android:textSize="13sp">
</EditText>
<ImageView
android:id="@+id/start_loc"
android:layout_width="20dp"
android:layout_height="17dp"
android:layout_centerVertical="true"
android:layout_marginLeft="17dp"
android:src="@drawable/start_icon" />
</RelativeLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="42dp"
android:layout_marginTop="23dp"
android:layout_marginRight="62dp"
android:layout_below="@+id/startpoint"
android:background="@drawable/blue_border_rounded_cornwe">
<EditText
android:id="@+id/dropLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/dest_loc"
android:background="@android:color/transparent"
android:hint="Password"
android:maxLines="1"
android:paddingLeft="17dp"
android:paddingTop="15dp"
android:paddingBottom="15dp"
android:textSize="13sp">
</EditText>
<ImageView
android:id="@+id/dest_loc"
android:layout_width="20dp"
android:layout_height="17dp"
android:layout_centerVertical="true"
android:layout_marginLeft="17dp"
android:src="@drawable/dest_icon" />
</RelativeLayout>
<ImageView
android:id="@+id/customCurrentLocation"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginRight="10dp"
android:baselineAlignBottom="true"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:src="@drawable/location_icon"/>
</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 can learn how to search the hospitals located by source and destination address with HMS Core Kits such as Map, Site, and Location Kits. Map kit is to display maps, it covers map data of more than 200 countries and regions for searching any location address. Location kit provides to get the current location and location updates, and it provides flexible location based services globally to the users. Site kit provides with convenient and secure access to diverse, place-related services to users.
I hope you have read this article. If you found it is helpful, please provide likes and comments.
Reference
Map Kit - Documentation
Map Kit – Training Video
Location Kit – Documentation
Location Kit – Training Video
Site Kit

Capture Hospital details using a Barcode scan by Huawei Scan kit in Android (Kotlin) – Part 6

{
"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"
}
Introduction
In this article, we can learn how to save the hospital details by scanning the barcode and saving the details in your contacts directory using Huawei Scan Kit. Due to busy days like journey, office work and personal work, users are not able to save many details. So, this app helps you to save the hospital information by just one scan of barcode from your phone such as Hospital Name, Contact Number, Email address, Website etc.
So, I will provide a series of articles on this Patient Tracking App, in upcoming articles I will integrate other Huawei Kits.
If you are new to this application, follow my previous articles.
https://forums.developer.huawei.com/forumPortal/en/topic/0201902220661040078
https://forums.developer.huawei.com/forumPortal/en/topic/0201908355251870119
https://forums.developer.huawei.com/forumPortal/en/topic/0202914346246890032
https://forums.developer.huawei.com/forumPortal/en/topic/0202920411340450018
https://forums.developer.huawei.com/forumPortal/en/topic/0202926518891830059
What is scan kit?
HUAWEI Scan Kit scans and parses all major 1D and 2D barcodes and generates QR codes, helps you to build quickly barcode scanning functions into your apps.
HUAWEI Scan Kit automatically detects, magnifies and identifies barcodes from a distance and also it can scan a very small barcode in the same way. It supports 13 different formats of barcodes, as follows.
1D barcodes: EAN-8, EAN-13, UPC-A, UPC-E, Codabar, Code 39, Code 93, Code 128 and ITF
2D barcodes: QR Code, Data Matrix, PDF 417 and Aztec
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 installed.
4. Minimum API Level 19 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 tick icon, 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.
Java:
maven { url 'http://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
9. Add the below plugin and dependencies in build.gradle(Module) file.
Java:
apply plugin: 'com.huawei.agconnect'
// Huawei AGC
implementation 'com.huawei.agconnect:agconnect-core:1.5.0.300'
// Scan Kit
implementation 'com.huawei.hms:scan:1.2.5.300'
10. Now Sync the gradle.
11. Add the required permission to the AndroidManifest.xml file.
Java:
<!-- Camera permission -->
<uses-permission android:name="android.permission.CAMERA" />
<!-- File read permission -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
Let us move to development
I have created a project on Android studio with empty activity let's start coding.
In the ScanActivity.kt we can find the button click.
Java:
class ScanActivity : AppCompatActivity() {
companion object{
private val CUSTOMIZED_VIEW_SCAN_CODE = 102
}
private var resultText: TextView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_scan)
resultText = findViewById<View>(R.id.result) as TextView
requestPermission()
}
fun onCustomizedViewClick(view: View?) {
resultText!!.text = ""
this.startActivityForResult(Intent(this, BarcodeScanActivity::class.java), CUSTOMIZED_VIEW_SCAN_CODE)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode != RESULT_OK || data == null) {
return
}
// Get return value of HmsScan from the value returned by the onActivityResult method by ScanUtil.RESULT as key value.
val obj: HmsScan? = data.getParcelableExtra(ScanUtil.RESULT)
try {
val json = JSONObject(obj!!.originalValue)
// Log.e("Scan","Result "+json.toString())
val name = json.getString("hospital name")
val phone = json.getString("phone")
val mail = json.getString("email")
val web = json.getString("site")
val i = Intent(Intent.ACTION_INSERT_OR_EDIT)
i.type = ContactsContract.Contacts.CONTENT_ITEM_TYPE
i.putExtra(ContactsContract.Intents.Insert.NAME, name)
i.putExtra(ContactsContract.Intents.Insert.PHONE, phone)
i.putExtra(ContactsContract.Intents.Insert.EMAIL, mail)
i.putExtra(ContactsContract.Intents.Insert.COMPANY, web)
startActivity(i)
} catch (e: JSONException) {
e.printStackTrace()
Toast.makeText(this, "JSON exception", Toast.LENGTH_SHORT).show()
} catch (e: Exception) {
e.printStackTrace()
Toast.makeText(this, "Exception", Toast.LENGTH_SHORT).show()
}
}
private fun requestPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(arrayOf(android.Manifest.permission.CAMERA, READ_EXTERNAL_STORAGE),1001)
}
}
@SuppressLint("MissingSuperCall")
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String?>, grantResults: IntArray) {
if (permissions == null || grantResults == null || grantResults.size < 2 || grantResults[0] != PackageManager.PERMISSION_GRANTED || grantResults[1] != PackageManager.PERMISSION_GRANTED) {
requestPermission()
}
}
}
In the BarcodeScanActivity.kt we can find the code to scan barcode.
Java:
class BarcodeScanActivity : AppCompatActivity() {
companion object {
private var remoteView: RemoteView? = null
//val SCAN_RESULT = "scanResult"
var mScreenWidth = 0
var mScreenHeight = 0
//scan view finder width and height is 350dp
val SCAN_FRAME_SIZE = 300
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_barcode_scan)
// 1. get screen density to calculate viewfinder's rect
val dm = resources.displayMetrics
val density = dm.density
// 2. get screen size
mScreenWidth = resources.displayMetrics.widthPixels
mScreenHeight = resources.displayMetrics.heightPixels
val scanFrameSize = (SCAN_FRAME_SIZE * density).toInt()
// 3. Calculate viewfinder's rect, it is in the middle of the layout.
// set scanning area(Optional, rect can be null. If not configure, default is in the center of layout).
val rect = Rect()
rect.left = mScreenWidth / 2 - scanFrameSize / 2
rect.right = mScreenWidth / 2 + scanFrameSize / 2
rect.top = mScreenHeight / 2 - scanFrameSize / 2
rect.bottom = mScreenHeight / 2 + scanFrameSize / 2
// Initialize RemoteView instance and set calling back for scanning result.
remoteView = RemoteView.Builder().setContext(this).setBoundingBox(rect).setFormat(HmsScan.ALL_SCAN_TYPE).build()
remoteView?.onCreate(savedInstanceState)
remoteView?.setOnResultCallback(OnResultCallback { result -> //judge the result is effective
if (result != null && result.size > 0 && result[0] != null && !TextUtils.isEmpty(result[0].getOriginalValue())) {
val intent = Intent()
intent.putExtra(ScanUtil.RESULT, result[0])
setResult(RESULT_OK, intent)
this.finish()
}else{
Log.e("Barcode","Barcode: No barcode recognized ")
}
})
// Add the defined RemoteView to page layout.
val params = FrameLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
val frameLayout = findViewById<FrameLayout>(R.id.rim1)
frameLayout.addView(remoteView, params)
}
// Manage remoteView lifecycle
override fun onStart() {
super.onStart()
remoteView?.onStart()
}
override fun onResume() {
super.onResume()
remoteView?.onResume()
}
override fun onPause() {
super.onPause()
remoteView?.onPause()
}
override fun onDestroy() {
super.onDestroy()
remoteView?.onDestroy()
}
override fun onStop() {
super.onStop()
remoteView?.onStop()
}
}
In the activity_scan.xml we can create the UI screen.
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
android:gravity="center"
tools:context=".scan.ScanActivity">
<Button
android:id="@+id/btn_click"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:textAllCaps="false"
android:textSize="20sp"
android:layout_gravity="center"
android:text="Click to Scan"
android:onClick="onCustomizedViewClick"
tools:ignore="OnClick" />
<TextView
android:id="@+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:layout_marginTop="80dp"
android:textColor="#C0F81E"/>
</LinearLayout>
In the activity_barcode_scan.xml we can create the frame layout.
XML:
<?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=".scan.BarcodeScanActivity">
// customize layout for camera preview to scan
<FrameLayout
android:id="@+id/rim1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#C0C0C0" />
// customize scanning mask
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:layout_centerHorizontal="true"
android:alpha="0.1"
android:background="#FF000000"/>
// customize scanning view finder
<ImageView
android:id="@+id/scan_view_finder"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerInParent="true"
android:layout_centerHorizontal="true"
android:background="#1f00BCD4"
tools:ignore="MissingConstraints" />
</RelativeLayout>
Demo
Find the demo in attachment or click here for original content.
Tips and Tricks
1. Make sure you are already registered as Huawei developer.
2. Set minSDK version to 19 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 can learn how to save the hospital details by scanning the barcode and saving the details in your contacts directory using Huawei Scan Kit. Due to busy days like journey, office work and personal work, users are not able to save many details. So, this app helps you to save the hospital information by just one scan of barcode from your phone such as Hospital Name, Contact Number, Email address, Website etc.
Reference
Scan Kit - Customized View
Scan Kit - Training Video

Integration of the Roll Ads feature of Huawei Ads Kit in Android app (Kotlin)

{
"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"
}
Introduction
In this article, we can learn how to integrate Roll Ads feature of Huawei Ads Kit into the android app. So, Roll ads are displayed as short videos or images, before, during, or after the video content is played.
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 Roll 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.
Java:
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.
Java:
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.
Java:
// 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.
Java:
class MainActivity : AppCompatActivity() {
private var videoContent: TextView? = null
private var skipAd: TextView? = null
private var countDown: TextView? = null
private var callToAction: TextView? = null
private var loadButton: Button? = null
private var registerButton: Button? = null
private var muteButton: Button? = null
private var pauseButton: Button? = null
private var instreamContainer: RelativeLayout? = null
private var instreamView: InstreamView? = null
private var whyThisAd: ImageView? = null
private var context: Context? = null
private var maxAdDuration = 0
private var whyThisAdUrl: String? = null
private var isMuted = false
private var adLoader: InstreamAdLoader? = null
private var instreamAds: List<InstreamAd>? = ArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
context = applicationContext
setTitle(R.string.instream_ad)
initInstreamAdView()
initButtons()
configAdLoader()
}
private val mediaChangeListener = InstreamMediaChangeListener { instreamAd ->
whyThisAdUrl = null
whyThisAdUrl = instreamAd.whyThisAd
Log.i(TAG, "onSegmentMediaChange, whyThisAd: $whyThisAdUrl")
if (!TextUtils.isEmpty(whyThisAdUrl)) {
whyThisAd!!.visibility = View.VISIBLE
whyThisAd!!.setOnClickListener { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(whyThisAdUrl))) }
} else {
whyThisAd!!.visibility = View.GONE
}
val cta = instreamAd.callToAction
if (!TextUtils.isEmpty(cta)) {
callToAction!!.visibility = View.VISIBLE
callToAction!!.text = cta
instreamView!!.callToActionView = callToAction
}
}
private val mediaStateListener: InstreamMediaStateListener = object : InstreamMediaStateListener {
override fun onMediaProgress(per: Int, playTime: Int) {
updateCountDown(playTime.toLong())
}
override fun onMediaStart(playTime: Int) {
updateCountDown(playTime.toLong())
}
override fun onMediaPause(playTime: Int) {
updateCountDown(playTime.toLong())
}
override fun onMediaStop(playTime: Int) {
updateCountDown(playTime.toLong())
}
override fun onMediaCompletion(playTime: Int) {
updateCountDown(playTime.toLong())
playVideo()
}
override fun onMediaError(playTime: Int, errorCode: Int, extra: Int) {
updateCountDown(playTime.toLong())
}
}
private val mediaMuteListener: MediaMuteListener = object : MediaMuteListener {
override fun onMute() {
isMuted = true
Toast.makeText(context, "Ad muted", Toast.LENGTH_SHORT).show()
}
override fun onUnmute() {
isMuted = false
Toast.makeText(context, "Ad unmuted", Toast.LENGTH_SHORT).show()
}
}
private fun initInstreamAdView() {
instreamContainer = findViewById(R.id.instream_ad_container)
videoContent = findViewById(R.id.instream_video_content)
skipAd = findViewById(R.id.instream_skip)
skipAd!!.setOnClickListener(View.OnClickListener {
if (null != instreamView) {
instreamView!!.onClose()
instreamView!!.destroy()
instreamContainer!!.visibility = View.GONE
}
})
countDown = findViewById(R.id.instream_count_down)
callToAction = findViewById(R.id.instream_call_to_action)
whyThisAd = findViewById(R.id.instream_why_this_ad)
instreamView = findViewById(R.id.instream_view)
instreamView!!.setInstreamMediaChangeListener(mediaChangeListener)
instreamView!!.setInstreamMediaStateListener(mediaStateListener)
instreamView!!.setMediaMuteListener(mediaMuteListener)
instreamView!!.setOnInstreamAdClickListener(InstreamView.OnInstreamAdClickListener {
Toast.makeText(context,"instream clicked.", Toast.LENGTH_SHORT).show()
})
}
private val clickListener = View.OnClickListener { view ->
when (view.id) {
R.id.instream_load -> if (null != adLoader) {
loadButton!!.text = getString(R.string.instream_loading)
adLoader!!.loadAd(AdParam.Builder().build())
}
R.id.instream_register -> if (null == instreamAds || instreamAds!!.isEmpty()) {
playVideo()
} else {
playInstreamAds(instreamAds!!)
}
R.id.instream_mute -> if (isMuted) {
instreamView!!.unmute()
muteButton!!.text = getString(R.string.instream_mute)
} else {
instreamView!!.mute()
muteButton!!.text = getString(R.string.instream_unmute)
}
R.id.instream_pause_play -> if (instreamView!!.isPlaying) {
instreamView!!.pause()
pauseButton!!.text = getString(R.string.instream_play)
} else {
instreamView!!.play()
pauseButton!!.text = getString(R.string.instream_pause)
}
else -> {
}
}
}
private fun initButtons() {
loadButton = findViewById(R.id.instream_load)
registerButton = findViewById(R.id.instream_register)
muteButton = findViewById(R.id.instream_mute)
pauseButton = findViewById(R.id.instream_pause_play)
loadButton!!.setOnClickListener(clickListener)
registerButton!!.setOnClickListener(clickListener)
muteButton!!.setOnClickListener(clickListener)
pauseButton!!.setOnClickListener(clickListener)
}
private val instreamAdLoadListener: InstreamAdLoadListener = object : InstreamAdLoadListener {
override fun onAdLoaded(ads: MutableList<InstreamAd>) {
if (null == ads || ads.size == 0) {
playVideo()
return
}
val it = ads.iterator()
while (it.hasNext()) {
val ad = it.next()
if (ad.isExpired) {
it.remove()
}
}
if (ads.size == 0) {
playVideo()
return
}
loadButton!!.text = getString(R.string.instream_loaded)
instreamAds = ads
Toast.makeText(context, "onAdLoaded, ad size: " + ads.size + ", click REGISTER to play.", Toast.LENGTH_SHORT).show()
}
override fun onAdFailed(errorCode: Int) {
Log.w(TAG, "onAdFailed: $errorCode")
loadButton!!.text = getString(R.string.instream_load)
Toast.makeText(context, "onAdFailed: $errorCode", Toast.LENGTH_SHORT).show()
playVideo()
}
}
private fun configAdLoader() {
// if the maximum total duration is 60 seconds and the maximum number of roll ads is eight,
// at most four 15-second roll ads or two 30-second roll ads will be returned.
// If the maximum total duration is 120 seconds and the maximum number of roll ads is four,
// no more roll ads will be returned after whichever is reached.
val totalDuration = 60
val maxCount = 4
val builder = InstreamAdLoader.Builder(context, getString(R.string.instream_ad_id))
adLoader = builder.setTotalDuration(totalDuration)
.setMaxCount(maxCount)
.setInstreamAdLoadListener(instreamAdLoadListener)
.build()
}
// play your normal video content.
private fun playVideo() {
hideAdViews()
videoContent!!.setText(R.string.instream_normal_video_playing)
}
private fun hideAdViews() {
instreamContainer!!.visibility = View.GONE
}
private fun playInstreamAds(ads: List<InstreamAd>) {
maxAdDuration = getMaxInstreamDuration(ads)
instreamContainer!!.visibility = View.VISIBLE
loadButton!!.text = getString(R.string.instream_load)
instreamView!!.setInstreamAds(ads)
}
private fun updateCountDown(playTime: Long) {
val time = Math.round((maxAdDuration - playTime) / 1000.toFloat()).toString()
runOnUiThread { countDown!!.text = time + "s" }
}
private fun getMaxInstreamDuration(ads: List<InstreamAd>): Int {
var duration = 0
for (ad in ads) {
duration += ad.duration.toInt()
}
return duration
}
override fun onPause() {
super.onPause()
if (null != instreamView && instreamView!!.isPlaying) {
instreamView!!.pause()
pauseButton!!.text = getText(R.string.instream_play)
}
}
override fun onResume() {
super.onResume()
if (null != instreamView && !instreamView!!.isPlaying) {
instreamView!!.play()
pauseButton!!.text = getText(R.string.instream_pause)
}
}
override fun onDestroy() {
super.onDestroy()
if (null != instreamView) {
instreamView!!.removeInstreamMediaStateListener()
instreamView!!.removeInstreamMediaChangeListener()
instreamView!!.removeMediaMuteListener()
instreamView!!.destroy()
}
}
companion object {
private val TAG = MainActivity::class.java.simpleName
}
}
In the activity_main.xml we can create the UI screen.
Java:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RelativeLayout
android:id="@+id/your_video_content"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="@android:color/black">
<TextView
android:id="@+id/instream_video_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAlignment="center"
android:layout_centerInParent="true"
android:text="Your video content"
android:textColor="@android:color/white"/>
</RelativeLayout>
<RelativeLayout
android:id="@+id/instream_ad_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone">
<com.huawei.hms.ads.instreamad.InstreamView
android:id="@+id/instream_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<TextView
android:id="@+id/instream_skip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingVertical="3dp"
android:paddingHorizontal="5dp"
android:layout_alignStart="@id/instream_view"
android:layout_alignLeft="@id/instream_view"
android:layout_alignTop="@id/instream_view"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="8dp"
android:text="Skip"
android:textColor="@android:color/white"
android:textSize="16sp"
android:background="@drawable/emui_button_select"/>
<TextView
android:id="@+id/instream_count_down"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingVertical="3dp"
android:paddingHorizontal="5dp"
android:layout_alignEnd="@id/instream_view"
android:layout_alignRight="@id/instream_view"
android:layout_alignTop="@id/instream_view"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:layout_marginTop="8dp"
android:textColor="@android:color/white"
android:textSize="16sp"
android:background="@drawable/emui_button_select"/>
<TextView
android:id="@+id/instream_ad_flag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="@id/instream_view"
android:layout_alignLeft="@id/instream_view"
android:layout_alignBottom="@id/instream_view"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginBottom="8dp"
android:background="@drawable/emui_button_select"
android:gravity="center"
android:text="Ad"
android:textColor="@android:color/white"
android:textSize="8sp"
android:textStyle="bold" />
<ImageView
android:id="@+id/instream_why_this_ad"
android:layout_width="14dp"
android:layout_height="14dp"
android:layout_toEndOf="@id/instream_ad_flag"
android:layout_toRightOf="@id/instream_ad_flag"
android:layout_alignBottom="@id/instream_view"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
android:layout_marginBottom="8dp"
android:src="@drawable/app_whythisad_info"/>
<TextView
android:id="@+id/instream_call_to_action"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingVertical="3dp"
android:paddingHorizontal="5dp"
android:layout_alignEnd="@id/instream_view"
android:layout_alignRight="@id/instream_view"
android:layout_alignBottom="@id/instream_view"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="8dp"
android:text="Learn more"
android:textColor="@android:color/white"
android:textSize="16sp"
android:background="@drawable/emui_button_select"/>
</RelativeLayout>
<RelativeLayout
android:id="@+id/instream_ctrl_panel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingHorizontal="16dp"
android:paddingVertical="16dp"
android:layout_below="@id/your_video_content">
<LinearLayout
android:id="@+id/load_and_register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_centerHorizontal="true">
<Button
android:id="@+id/instream_load"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:text="Load Ad"/>
<Button
android:id="@+id/instream_register"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:text="Register"/>
</LinearLayout>
<LinearLayout
android:id="@+id/play_ctrl"
android:layout_below="@id/load_and_register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_centerHorizontal="true">
<Button
android:id="@+id/instream_mute"
android:layout_width="100dp"
android:layout_marginRight="10dp"
android:layout_height="wrap_content"
android:text="Mute"/>
<Button
android:id="@+id/instream_pause_play"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Pause"/>
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
</ScrollView>
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 Roll Ads feature of Huawei Ads Kit into the android app. So, Roll ads are displayed as short videos or images, before, during, or after the video content is played.
I hope you have read this article. If you found it is helpful, please provide likes and comments.
Reference
Ads Kit - Roll Ads
Ads Kit – Training Video

Categories

Resources