AD kit collections: Huawei vs AdMob - Huawei Developers

More information like this, you can visit HUAWEI Developer Forum​
What is Ad Kit
Ad kit service makes it easy for developers to raise money with high-quality advertising from mobile devices. It maximizes the value of every impression by combining global advertiser demand, innovative ad formats, and advanced app monetization technology.
Showing ads to app users helps you to create a reliable revenue stream to help your company grow while concentrating on creating and improving quality apps. Advertisers can attract new consumers and users can discover related goods and services while enjoying free apps. So it is a win for developers, users, and advertisers.
In this article we will integrate banner ad and reward video ad provided by Google Admob and Huawei Ad kit in single application.
Banner Ad
{
"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"
}
Rectangular advertising on the top or bottom of the screen show. When users interact with the app, banner ads remain on the screen and it can be refreshed periodically for a period of time.
Reward Ad
Ads which reward users for watching short videos, interacting with ads and surveys that are playable. Perfect for free-to-play players to monetize.
Usecase
1. We will develop small application “Wheel of fortune”. User can spin wheel to earn coins.
2. We will show banner ad at the bottom of app
3. User will spin the wheel of fortune, if coins earned are 6 or less ,he can earn additional coin by watching reward ads.
4. If device supports HMS, we will show Huawei ads.
5. If device supports GMS, we will show Google AdMob ads.
Initial Setup
Huawei Ad kit
1) Create a project in android studio
2) Get the SHA Key. For getting the SHA key we can refer to this article.
3) Create an app in the Huawei app gallery connect.
4) Provide the SHA Key in App Information Section.
5) Provide storage location.
6) After completing all the above points we need to download the agconnect-services.json from App Information Section. Copy and paste the Json file in the app folder of the android project.
7) Enter the below maven url inside the repositories of buildscript and allprojects ( project build.gradle file )
Code:
maven { url 'http://developer.huawei.com/repo/' }
8) Enter the below maven url inside the repositories of buildscript and allprojects (project build.gradle file)
Code:
implementation 'com.huawei.hms:ads-lite:13.4.30.307'
9) Provide following permissions in manifest.
Code:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Google Admob
1. Create a Google AdMob account and register an app.
2. Open app-level gradle file, and add following dependencies.
Code:
dependencies {
implementation 'com.google.android.gms:play-services-ads:19.2.0'
}
3. Create APP ID in admob dashboard. Refer this to create APP ID.
4. Add APP ID in Android manifest.
Code:
<manifest>
<application>
<!-- Sample AdMob App ID: ca-app-pub-3940256099942544~3347511713 -->
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy"/>
</application>
</manifest>
Development for Huawei device supporting HMS
Integrating Huawei Banner AD
1. Add bannerview in activity_main.xml
Code:
<RelativeLayout xmlns:hwads="http://schemas.android.com/apk/res-auto" >
<com.huawei.hms.ads.banner.BannerView
android:id="@+id/huawei_banner_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:visibility="gone"
hwads:adId="testw6vs28auh3"
hwads:bannerSize="BANNER_SIZE_360_57"/>
Note: We are using test ad ID. "testw6vs28auh3" is a dedicated test ad slot ID.
2. To show Banner Ad
Code:
if(Utility.isDeviceHuaweiManufacturer() && Utility.isHuaweiMobileServicesAvailable(this)) {
hwBannerView = findViewById(R.id.huawei_banner_view);
hwBannerView.setVisibility(View.VISIBLE);
// Create an ad request to load an ad.
AdParam adParam = new AdParam.Builder().build();
hwBannerView.loadAd(adParam);
hwBannerView.setAdListener(adListener);
} private AdListener adListener = new AdListener() {
@Override
public void onAdLoaded() {
// Called when an ad is loaded successfully.
Log.d(TAG , "onAdLoaded");
}
@Override
public void onAdFailed(int errorCode) {
// Called when an ad fails to be loaded.
Log.d(TAG , "onAdFailed");
}
@Override
public void onAdOpened() {
// Called when an ad is opened.
Log.d(TAG , "onAdOpened");
}
@Override
public void onAdClicked() {
// Called when a user taps an ad.
Log.d(TAG , "onAdClicked");
}
@Override
public void onAdLeave() {
// Called when a user has left the app.
Log.d(TAG , "onAdLeave");
}
@Override
public void onAdClosed() {
// Called when an ad is closed.
Log.d(TAG , "onAdClosed");
}
};
Integrating Huawei Reward Video AD
1. To show Huawei reward Ads
Code:
if (Utility.isHuaweiMobileServicesAvailable(MainActivity.this) && Utility.isDeviceHuaweiManufacturer()) {
showHuaweiRewardAds();
}
Code:
private void showHuaweiRewardAds() {
// Test ad slot ID
final String AD_ID = "testx9dtjwj8hp";
final RewardAd rewardAd;
rewardAd = new RewardAd(this, AD_ID);
RewardAdLoadListener listener= new RewardAdLoadListener() {
@Override
public void onRewardedLoaded() {
// Rewarded ad loaded successfully.
if (rewardAd.isLoaded()) {
rewardAd.show(MainActivity.this, new RewardAdStatusListener() {
@Override
public void onRewardAdOpened() {
// Rewarded ad opened.
Log.d(TAG , "rewardAd loaded");
}
@Override
public void onRewardAdFailedToShow(int errorCode) {
// Failed to display the rewarded ad.
Log.d(TAG , "rewardAd failed error : " + errorCode);
}
@Override
public void onRewardAdClosed() {
// Rewarded ad closed.
}
@Override
public void onRewarded(Reward reward){
showRewardAdAlertDialog( "You have been rewarded " +
String.valueOf(reward.getAmount()) +" "+ reward.getName() + " for watching Ad");
}
});
}
}
@Override
public void onRewardAdFailedToLoad(int errorCode) {
// Failed to load the rewarded ad.
}
};
rewardAd.loadAd(new AdParam.Builder().build(), listener);
}
2. The reward object is passed in the onRewarded method. Call the reward.getAmount() method to obtain the reward amount and the reward.getName() method to obtain the name of the reward.
Code:
public void onRewarded(Reward reward){
// Reward earned by the user.
// TODO: Reward the user.
// Toast.makeText(MainActivity.this , reward.getName() +", "+ reward.getAmount() , Toast.LENGTH_LONG).show();
showRewardAdAlertDialog( "You have been rewarded " +
String.valueOf(reward.getAmount()) +" "+ reward.getName() + " for watching Ad");
}
Development for Non Huawei device supporting GMS
Integrating AdMob Banner AD
Before loading ads, we have to initialize the Mobile Ads SDK by calling MobileAds.initialize() which initializes the SDK and calls back a completion listener once initialization is complete (or after a 30-second timeout). This needs to be done only once, ideally at app launch.
Code:
MobileAds.initialize(this, new OnInitializationCompleteListener() {
@Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
2. Add the banner AdView in activity_main.xml
Code:
<com.google.android.gms.ads.AdView
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="@+id/google_banner_adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:visibility="gone"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
ads:adSize="BANNER"
ads:adUnitId="ca-app-pub-3940256099942544/6300978111">
</com.google.android.gms.ads.AdView>
Note: Here we are using test adUnitId. When building and testing your apps, make sure you use test ads rather than live, production ads
3. To load the banner Ad view
Code:
if(Utility.isGooglePlayServicesAvailable(this)) {
mGoogleAdView = findViewById(R.id.google_banner_adView);
mGoogleAdView.setVisibility(View.VISIBLE);
AdRequest adRequest = new AdRequest.Builder().build();
mGoogleAdView.loadAd(adRequest);
mGoogleAdView.setAdListener(new com.google.android.gms.ads.AdListener()
{
@Override
public void onAdLoaded() {
// Code to be executed when an ad finishes loading.
Log.d(TAG, "onAdLoaded");
}
@Override
public void onAdFailedToLoad(int errorCode) {
// Code to be executed when an ad request fails.
Log.d(TAG, "onAdFailedToLoad " + errorCode);
}
@Override
public void onAdOpened() {
// Code to be executed when an ad opens an overlay that
// covers the screen.
}
@Override
public void onAdClicked() {
// Code to be executed when the user clicks on an ad.
}
@Override
public void onAdLeftApplication() {
// Code to be executed when the user has left the app.
}
@Override
public void onAdClosed() {
// Code to be executed when the user is about to return
// to the app after tapping on an ad.
}
}
);
}
Integrating AdMob Reward Video AD
1. To show Admob Reward Video ad.
Code:
if (Utility.isGooglePlayServicesAvailable(MainActivity.this)) {
showGoogleRewardAds();
}
Code:
private void showGoogleRewardAds() {
RewardedVideoAd mRewardedVideoAd;
MobileAds.initialize(this, "ca-app-pub-3940256099942544~3347511713");
// Use an activity context to get the rewarded video instance.
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(new RewardedVideoAdListener() {
@Override
public void onRewardedVideoAdLoaded() {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
}
}
@Override
public void onRewardedVideoAdOpened() {
}
@Override
public void onRewardedVideoStarted() {
}
@Override
public void onRewardedVideoAdClosed() {
}
@Override
public void onRewarded(RewardItem rewardItem) {
showRewardAdAlertDialog("You have been rewarded " + rewardItem.getAmount() + " "+ rewardItem.getType() + " for watching ad");
}
@Override
public void onRewardedVideoAdLeftApplication() {
}
@Override
public void onRewardedVideoAdFailedToLoad(int i) {
}
@Override
public void onRewardedVideoCompleted() {
}
});
mRewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917",
new AdRequest.Builder().build());
}
"ca-app-pub-3940256099942544/5224354917" is test Ad id for Admob reward AD.
To check if device has HMS or GMS installed
Code:
public class Utility {
public static boolean isGooglePlayServicesAvailable(Activity activity) {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int status = googleApiAvailability.isGooglePlayServicesAvailable(activity);
if(status != ConnectionResult.SUCCESS) {
if(googleApiAvailability.isUserResolvableError(status)) {
googleApiAvailability.getErrorDialog(activity, status, 2404).show();
}
return false;
}
return true;
}
public static boolean isHuaweiMobileServicesAvailable(Context context) {
if (HuaweiApiAvailability.getInstance().isHuaweiMobileServicesAvailable(context) == ConnectionResult.SUCCESS){
return true;
}
return false;
}
public static boolean isDeviceHuaweiManufacturer () {
String manufacturer = Build.MANUFACTURER;
Log.d("Device : " , manufacturer);
if (manufacturer.toLowerCase().contains("huawei")) {
return true;
}
return false;
}
}
Links:
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides-V5/publisher-service-introduction-0000001050064960-V5
https://developers.google.com/admob/android/quick-start

Related

How to Develop a Reward Ads in 10 Min ?

This article is originally from HUAWEI Developer Forum.
Forum link: https://forums.developer.huawei.com/forumPortal/en/home
{
"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"
}
Huawei Ads provide developers an extensive data capabilities to deliver high quality ad content to their users. By integrating HMS ads kit we can start earning right away. It is very useful particularly when we are publishing a free app and want to earn some money from it.
Integrating HMS ads kit does not take more than 10 mins. HMS ads kit currently offers five types of ad format:
v Banner Ad: Banner ads are rectangular images that occupy a spot at the top, middle, or bottom within an app's layout. 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.
v Native Ad: Native ads fit seamlessly into the surrounding content to match our app design. Such ads can be customized as needed.
v Reward Ad: Rewarded ads are full-screen video ads that reward users for watching.
v Interstitial Ad: Interstitial ads are full-screen ads that cover the interface of an app. Such ads are displayed when a user starts, pauses, or exits an app, without disrupting the user's experience.
v Splash Ad: Splash ads are displayed immediately after an app is launched, even before the home screen of the app is displayed.
Today in this article we are going to learn how to integrate Reward Ad into our apps.
Prerequisite
1) Must have a Huawei Developer Account
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.
Things Need To Be Done
1) First we need to create a project in android studio.
2) Get the SHA Key. For getting the SHA key we can refer to this article.
3) Create an app in the Huawei app gallery connect.
4) Provide the SHA Key in App Information Section.
5) Provide storage location.
6) After completing all the above points we need to download the agconnect-services.json from App Information Section. Copy and paste the Json file in the app folder of the android project.
7) Copy and paste the below maven url inside the repositories of buildscript and allprojects ( project build.gradle file )
maven { url 'http://developer.huawei.com/repo/' }
8) Copy and paste the below plugin in the app build.gradle file dependencies section.
implementation 'com.huawei.hms:ads-lite:13.4.28.305'
9) If the project is using progaurd, copy and paste the below code in the progaurd-rules.pro file.
Code:
-keep class com.huawei.openalliance.ad.** { *; }
-keep class com.huawei.hms.ads.** { *; }
10) The HUAWEI Ads SDK requires the following permissions:
a) android.permission.ACCESS_NETWORK_STATE
b) android.permission.ACCESS_WIFI_STATE
11) Now sync the app.
There are two ways we can use Reward Ad in to our aps.
1. Showing Reward ad after splash screen.
2. Using Reward ad in a game.
Reward Ad after splash screen
In this scenario, we will show reward ad after displaying few seconds of splash screen.
STEPS
1) Create a RewardAd Object and use it call loadAd() method to load an Ad. Place it in onCreate() method.
Code:
private void loadRewardAd() {
if (rewardAd == null) {
rewardAd = new RewardAd(SplashActivity.this, AD_ID);
}
RewardAdLoadListener listener= new RewardAdLoadListener() {
@Override
public void onRewardedLoaded() {
// Rewarded ad loaded successfully...
}
@Override
public void onRewardAdFailedToLoad(int errorCode) {
// Failed to load the rewarded ad...
}
};
rewardAd.loadAd(new AdParam.Builder().build(),listener);
}
2) Call the isLoaded() method to confirm that an ad has finished loading, and call the show() method of the RewardAd object to display the ad.
Code:
private void rewardAdShow() {
if(rewardAd.isLoaded()) {
rewardAd.show(SplashActivity.this, new RewardAdStatusListener() {
@Override
public void onRewardAdClosed() {
super.onRewardAdClosed();
goToMainPage();
}
@Override
public void onRewardAdFailedToShow(int i) {
super.onRewardAdFailedToShow(i);
goToMainPage();
}
@Override
public void onRewardAdOpened() {
super.onRewardAdOpened();
}
@Override
public void onRewarded(Reward reward) {
super.onRewarded(reward);
goToMainPage();
}
});
}
else{
goToMainPage();
}
}
3) A handler to call rewardAdShow() method after few seconds. Place it in the onCreate() method after loadRewardAd() method.
Code:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
rewardAdShow();
}
}, 1000);
4) When testing rewarded ads, use the dedicated test ad slot ID to obtain test ads. This avoids invalid ad clicks during the test. The test ad slot ID is used only for function commissioning. Before releasing your app, apply for a formal ad slot ID and replace the test ad slot ID with the formal one.
THE RESULT
Reward Ad in a Game
In this scenario, we will show Reward Ad in a game and how user will get rewards after watching the ad. In real scenario user gets rewards in terms of extra coins, advance weapon, extra bullets for a weapon, extra life etc.
Here we will showcase how user gets extra life in a game after watching Reward Ad. The name of the game is Luck By Chance.
GAME RULES
· The game will generate a random number between 1 - 1000.
· The player needs to guess that number.
· Suppose the number is 200, the player guess the number as 190. Then the game will let the player know that the number is too low.
· If the player guess the number as 210. Then the game will let the player know that the number is too high.
· The player gets 3 life that means the player has 3 chance to guess the number right.
· If the player exhaust his / her 3 life then the game will give a chance to the player to watch Reward Ad video to get an extra life i.e. 1 life.
· After watching the Reward Ad video player can play one more chance and if the player guess it right then he / she wins the game.
· If the player wins the game, the player gets 5 score. The score gets added by 5 each time the player wins the game.
STEPS
1) Generate Random Number
Code:
public static final int MAX_NUMBER = 1000;
public static final Random RANDOM = new Random();
Code:
private void newGamePlay() {
findTheNumber = RANDOM.nextInt(MAX_NUMBER) + 5;
edtGuessNumber.setText("");
if (!blnScore) {
numScore = 0;
}
txtScore.setText("Score " + numScore);
numberTries = 3;
setLife(numberTries);
}
2) Create a method to play the game. Here we will check whether the guess number is too high or too low and if the user guess it right then we will show a win message to the user.
Code:
private void playTheGame() {
int guessNumber = Integer.parseInt(edtGuessNumber.getText().toString());
if (numberTries <= 0) {
showAdDialog();
} else {
if (guessNumber == findTheNumber) {
txtResult.setText("Congratulations ! You found the number " + findTheNumber);
numScore +=5;
blnScore = true;
newGamePlay();
} else if (guessNumber > findTheNumber) {
numberTries--;
setLife(numberTries);
if(numScore >0) {
numScore -= 1;
}
txtResult.setText(R.string.high);
} else {
numberTries--;
setLife(numberTries);
if(numScore >0) {
numScore -= 1;
}
txtResult.setText(R.string.low);
}
}
}
3) Create a RewardAd Object and use it call loadAd() method to load an Ad. Place it in onCreate() method.
Code:
private void loadRewardAd() {
if (rewardedAd == null) {
rewardedAd = new RewardAd(RewardActivity.this, AD_ID);
}
RewardAdLoadListener rewardAdLoadListener = new RewardAdLoadListener() {
@Override
public void onRewardAdFailedToLoad(int errorCode) {
Toast.makeText(RewardActivity.this,
"onRewardAdFailedToLoad "
+ "errorCode is :"
+ errorCode, Toast.LENGTH_SHORT).show();
}
@Override
public void onRewardedLoaded() {
}
};
rewardedAd.loadAd(new AdParam.Builder().build(), rewardAdLoadListener);
}
4) Call the isLoaded() method to confirm that an ad has finished loading, and call the show() method of the RewardAd object to display the ad. After user watch the entire Reward Ad video, he/she will get extra life i.e. 1.
Code:
private void rewardAdShow() {
if (rewardedAd.isLoaded()) {
rewardedAd.show(RewardActivity.this, new RewardAdStatusListener() {
@Override
public void onRewardAdClosed() {
loadRewardAd();
}
@Override
public void onRewardAdFailedToShow(int errorCode) {
Toast.makeText(RewardActivity.this,
"onRewardAdFailedToShow "
+ "errorCode is :"
+ errorCode,
Toast.LENGTH_SHORT).show();
}
@Override
public void onRewardAdOpened() {
Toast.makeText(RewardActivity.this,
"onRewardAdOpened",
Toast.LENGTH_SHORT).show();
}
@Override
public void onRewarded(Reward reward) {
numberTries ++; // HERE USER WILL GET REWARD AFTER WATCHING REWARD Ad VIDEO ...
setLife(numberTries);
}
});
}
}
5) A dialog to show the user that he/she needs to watch the video to get extra life. Here we will call rewardAdShow() method to show the reward video to the user for extra life if he/she accept to continue the game.
Code:
private void showAdDialog() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("GET EXTRA LIFE");
alertDialogBuilder
.setMessage("Watch video to get extra life")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
rewardAdShow();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
THE CODE
RewardActivity.java
Code:
public class RewardActivity extends AppCompatActivity implements View.OnClickListener {
public static final int MAX_NUMBER = 1000;
public static final Random RANDOM = new Random();
private static final String AD_ID = "testx9dtjwj8hp";
TextView txtHeader, txtScore, txtLife, txtResult;
EditText edtGuessNumber;
Button btnGuess;
boolean blnScore = false;
private int findTheNumber, numberTries, numScore = 1;
private RewardAd rewardedAd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reward);
txtHeader = findViewById(R.id.txtHeader);
txtHeader.setText("LUCK BY CHANCE");
txtLife = findViewById(R.id.txtLife);
txtScore = findViewById(R.id.txtScore);
txtResult = findViewById(R.id.txtStatus);
edtGuessNumber = findViewById(R.id.edtGuessNumber);
btnGuess = findViewById(R.id.btnGuess);
btnGuess.setOnClickListener(this);
newGamePlay();
loadRewardAd();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnGuess:
playTheGame();
break;
}
}
@SuppressLint("SetTextI18n")
private void playTheGame() {
int guessNumber = Integer.parseInt(edtGuessNumber.getText().toString());
if (numberTries <= 0) {
showAdDialog();
} else {
if (guessNumber == findTheNumber) {
txtResult.setText("Congratulations ! You found the number " + findTheNumber);
numScore +=5;
blnScore = true;
newGamePlay();
} else if (guessNumber > findTheNumber) {
numberTries--;
setLife(numberTries);
if(numScore >0) {
numScore -= 1;
}
txtResult.setText(R.string.high);
} else {
numberTries--;
setLife(numberTries);
if(numScore >0) {
numScore -= 1;
}
txtResult.setText(R.string.low);
}
}
}
private void showAdDialog() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("GET EXTRA LIFE");
alertDialogBuilder
.setMessage("Watch video to get extra life")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
rewardAdShow();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
@SuppressLint("SetTextI18n")
private void newGamePlay() {
findTheNumber = RANDOM.nextInt(MAX_NUMBER) + 5;
edtGuessNumber.setText("");
if (!blnScore) {
numScore = 0;
}
txtScore.setText("Score " + numScore);
numberTries = 3;
setLife(numberTries);
}
private void loadRewardAd() {
if (rewardedAd == null) {
rewardedAd = new RewardAd(RewardActivity.this, AD_ID);
}
RewardAdLoadListener rewardAdLoadListener = new RewardAdLoadListener() {
@Override
public void onRewardAdFailedToLoad(int errorCode) {
Toast.makeText(RewardActivity.this,
"onRewardAdFailedToLoad "
+ "errorCode is :"
+ errorCode, Toast.LENGTH_SHORT).show();
}
@Override
public void onRewardedLoaded() {
}
};
rewardedAd.loadAd(new AdParam.Builder().build(), rewardAdLoadListener);
}
private void rewardAdShow() {
if (rewardedAd.isLoaded()) {
rewardedAd.show(RewardActivity.this, new RewardAdStatusListener() {
@Override
public void onRewardAdClosed() {
loadRewardAd();
}
@Override
public void onRewardAdFailedToShow(int errorCode) {
Toast.makeText(RewardActivity.this,
"onRewardAdFailedToShow "
+ "errorCode is :"
+ errorCode,
Toast.LENGTH_SHORT).show();
}
@Override
public void onRewardAdOpened() {
Toast.makeText(RewardActivity.this,
"onRewardAdOpened",
Toast.LENGTH_SHORT).show();
}
@Override
public void onRewarded(Reward reward) {
numberTries ++;
setLife(numberTries);
}
});
}
}
private void setLife(int life) {
txtLife.setText("Life " + life);
}
}
activity_reward.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="match_parent"
tools:context=".RewardActivity">
<include
android:id="@+id/include"
layout="@layout/layout_bar"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/edtGuessNumber"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginStart="32dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="32dp"
android:background="@drawable/edittext_style"
android:ems="10"
android:paddingStart="10dp"
android:paddingEnd="10dp"
android:inputType="number|none"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView3"
app:layout_constraintVertical_bias="0.0" />
<TextView
android:id="@+id/txtLife"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:layout_marginEnd="24dp"
android:textColor="#0B400F"
android:textSize="24sp"
app:layout_constraintBottom_toTopOf="@+id/textView3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/include"
app:layout_constraintVertical_bias="0.00999999" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="200dp"
android:text="Guess The Number ?"
android:textColor="#3040E4"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/include"
app:layout_constraintVertical_bias="0.0" />
<Button
android:id="@+id/btnGuess"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_marginStart="32dp"
android:layout_marginTop="70dp"
android:layout_marginEnd="32dp"
android:background="#F57F17"
android:text="@string/play"
android:textColor="#FFFFFF"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/edtGuessNumber"
app:layout_constraintVertical_bias="0.0" />
<TextView
android:id="@+id/txtStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:textColor="#1B5E20"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/edtGuessNumber"
app:layout_constraintVertical_bias="0.0" />
<TextView
android:id="@+id/txtScore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="24dp"
android:layout_marginTop="32dp"
android:text="Score 0"
android:textColor="#B71C1C"
android:textSize="24sp"
app:layout_constraintBottom_toTopOf="@+id/textView3"
app:layout_constraintEnd_toStartOf="@+id/txtLife"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/include"
app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
THE RESULT
About the reward ad in the game.. is there a way to skip the ad but still end up getting the reward?
thanks for sharing very easy to implement

Account Authorization : Huawei vs Google

More information like this, you can visit HUAWEI Developer Forum​
In this article, we will integrate various sign-in options in our single android application using Huawei Account kit and Google Sign-In.
Use case:
To allow user to sign in either by Huawei account or Google account by if device has HMS or GMS respectively.
Allow user to sign in using Huawei if device has HMS.
Allow user to sign in using Google if device has GMS.
{
"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"
}
Huawei Account kit
Prerequisite
1) You must have Huawei developer account.
2) Huawei phone with HMS 4.0.0.300 or later
3) Android Studio, Jdk 1.8, SDK platform 26 and Gradle 4.6 installed.
Setup:
1) Create a project in android studio.
2) Get the SHA-256 Key.
3) Create an app in the Huawei app gallery connect.
4) Enable account kit setting in Manage APIs section.
5) Provide the SHA-256 Key in App Information Section.
6) Provide storage location.
7) Enable Huwaei account under Auth Service in AGC
8) After completing all the above points we need to download the agconnect-services.json from App Information Section. Place the json file in the app folder of the android project.
9) Enter the below maven url inside the repositories of buildscript and allprojects respectively ( project build.gradle file )
Code:
maven { url 'http://developer.huawei.com/repo/' }
10) Enter the below plugin in the app build.gradle file
Code:
apply plugin: 'com.huawei.agconnect'
dependencies {
implementation 'com.huawei.hms:hwid:4.0.0.300'
}
11) Now Sync the gradle.
Implementation
1) In this article, we will implement Authorization code method.
Code:
HuaweiIdAuthParams authParams = new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setAuthorizationCode().createParams();
huaweiservice = HuaweiIdAuthManager.getService(MainActivity.this, authParams);
startActivityForResult(huaweiservice.getSignInIntent(), HUAWEI_SIGNIN);
2) To Process the sign-in result after the authorization is complete.
Code:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == HUAWEI_SIGNIN) {
com.huawei.hmf.tasks.Task<AuthHuaweiId> authHuaweiIdTask = HuaweiIdAuthManager.parseAuthResultFromIntent(data);
if (authHuaweiIdTask.isSuccessful()) {
//The sign-in is successful, and the user's HUAWEI ID information and authorization code are obtained.
AuthHuaweiId huaweiAccount = authHuaweiIdTask.getResult();
Log.i(TAG, "Authorization code:" + huaweiAccount.getAuthorizationCode());
Log.d(TAG, "name: " + huaweiAccount.getDisplayName());
Log.d(TAG, "email: " + huaweiAccount.getEmail());
Log.d(TAG , "avatar : "+huaweiAccount.getAvatarUriString());
launchLoggedinActivity(huaweiAccount.getFamilyName() , huaweiAccount.getGivenName() , huaweiAccount.getAvatarUriString(),"huawei");
} else {
// The sign-in failed.
Log.e(TAG, "sign in failed : " + ((com.huawei.hms.common.ApiException) authHuaweiIdTask.getException()).getStatusCode());
}
}
}
3) To handle silent Sign-in
The authorization is required only on first registration with the HUAWEI ID. Then no approval is required for subsequent registrations with the same HUAWEI ID.
Code:
private void handleHuaweiSilentSignIn() {
HuaweiIdAuthParams authParams = new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM).createParams();
HuaweiIdAuthService service = HuaweiIdAuthManager.getService(MainActivity.this, authParams);
com.huawei.hmf.tasks.Task<AuthHuaweiId> task = service.silentSignIn();
task.addOnSuccessListener(new OnSuccessListener<AuthHuaweiId>() {
@Override
public void onSuccess(AuthHuaweiId authHuaweiId) {
// Obtain the user's HUAWEI ID information.
Log.i(TAG, "displayName:" + authHuaweiId.getDisplayName());
launchLoggedinActivity(authHuaweiId.getFamilyName() , authHuaweiId.getGivenName() , authHuaweiId.getAvatarUriString(),"huawei");
}
});
task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
// The sign-in failed. Try to sign in explicitly using getSignInIntent().
if (e instanceof ApiException) {
ApiException apiException = (ApiException)e;
Log.i(TAG, "sign failed status:" + apiException.getStatusCode());
}
}
});
}
4) To sign out from Huawei account
Code:
Task<Void> signOutTask = service.signOut();
signOutTask.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
Log.i(TAG, "signOut complete");
}
});
5) To revoke authorization
Code:
service.cancelAuthorization().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
if (task.isSuccessful()) {
// Processing after a successful authorization revoking.
Log.i(TAG, "onSuccess: ");
} else {
// Handle the exception.
Exception exception = task.getException();
if (exception instanceof ApiException){
int statusCode = ((ApiException) exception).getStatusCode();
Log.i(TAG, "onFailure: " + statusCode);
}
}
}
Google Sign in
1) To add google play services, In your projects root-level build.gradle file, ensure that Googles Maven repository is included:
Code:
allprojects {
repositories {
google()
// If you're using a version of Gradle lower than 4.1, you must instead use:
// maven {
// url 'https://maven.google.com'
// }:
}
}
2) In app-level build.gradle file, declare Google Play services as a dependency:
Code:
dependencies {
implementation 'com.google.android.gms:play-services-auth:18.1.0'
}
3) To specify your app's SHA-1 fingerprint, go to Settings page of the Firebase console. Refer to Authenticating Your Client for details on how to get your app's SHA-1 fingerprint.
4) Enable Google Sign-In in the Firebase console:
In the Firebase console, open the Auth section.
On Sign in method tab, enable the Google sign-in method and click Save.
5) To Configure Google Sign-in and the GoogleSignInClient object.
Code:
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
// Build a GoogleSignInClient with the options specified by gso.
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
6) To check for an existing sign-in user.
Code:
// Check for existing Google Sign In account, if the user is already signed in
// the GoogleSignInAccount will be non-null.
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
updateUI(account);
If GoogleSignInAccount instanse is not null, user is already signed in.
7) On click of google sign in button, we will create a sign-in intent with the getSignInIntent method, and starting the intent with startActivityForResult.
Code:
private View.OnClickListener googleClickListner = new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
};
8) To process the sign in result.
Code:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed, no need to attach
// a listener.
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleGoogleSignInResult(task);
}
} private void handleGoogleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
Log.d(TAG, "name: " + account.getDisplayName());
Log.d(TAG, "email: " + account.getEmail());
Log.d(TAG , "avatar : "+account.getPhotoUrl());
launchLoggedinActivity(account.getGivenName(), account.getFamilyName(),account.getPhotoUrl()!=null ? account.getPhotoUrl().toString():null, "google");
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
}
}
9) Code snippet for sign out from google is
Code:
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
GoogleSignInClient googleSignInClient = GoogleSignIn.getClient(LoggedInActivity.this, gso);
googleSignInClient.signOut();
Huawei and Google Sign in Button Integration
Add the following code in activity_main.xml
Code:
<?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:background="@drawable/background"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:visibility="gone"
android:id="@+id/login_layout"
android:orientation="vertical">
<com.google.android.gms.common.SignInButton
android:id="@+id/sign_in_button"
android:layout_width="242dp"
android:paddingLeft="15dp"
android:paddingRight="15dp"
android:visibility="gone"
android:layout_gravity="center_horizontal"
android:layout_height="wrap_content" />
<com.huawei.hms.support.hwid.ui.HuaweiIdAuthButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/hwi_sign_in"
android:layout_gravity="center_horizontal"
android:visibility="gone"
android:paddingTop="2dp"
android:paddingBottom="2dp"
android:background="#3b5998"
app:hwid_button_theme="hwid_button_theme_full_title"
app:hwid_corner_radius="hwid_corner_radius_small"
/>
</LinearLayout>
</RelativeLayout>
Permissions:
Add the following permissions in manifest.
Code:
<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" />
To check if device has HMS or GMS installed.
Code:
public class Utils {
public static boolean isSignedIn = false;
public static boolean isGooglePlayServicesAvailable(Activity activity) {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int status = googleApiAvailability.isGooglePlayServicesAvailable(activity);
if(status != ConnectionResult.SUCCESS) {
if(googleApiAvailability.isUserResolvableError(status)) {
googleApiAvailability.getErrorDialog(activity, status, 2404).show();
}
return false;
}
return true;
}
public static boolean isHuaweiMobileServicesAvailable(Context context) {
if (HuaweiApiAvailability.getInstance().isHuaweiMobileServicesAvailable(context) == ConnectionResult.SUCCESS){
return true;
}
return false;
}
public static boolean isDeviceHuaweiManufacturer () {
String manufacturer = Build.MANUFACTURER;
Log.d("Device : " , manufacturer);
if (manufacturer.toLowerCase().contains("huawei")) {
return true;
}
return false;
}
}
Conclusion
We have developed a single application to allow sign in using either by Huawei or google.
Reference
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/introduction-0000001050048870
https://developers.google.com/identity/sign-in/android/start-integrating​​

Huawei Flight Booking Application (Account kit and Ads kit)

More information like this, you can visit HUAWEI Developer Forum​
Introduction
Huawei Flight booking application is to explore HMS kits in real time scenario. This app can be used as reference to CP during HMS integration.
Prerequisite
1) You must have Huawei developer account.
2) Huawei phone with HMS 4.0.0.300 or later
3) Android Studio, JDK 1.8, SDK platform 26 and Gradle 4.6 installed.
Permissions
Provide following permissions in manifest.
Code:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
User Sign in
HUAWEI Account Kit offers easy, stable and fast login, and authorization functions to developers. Instead of entering accounts and passwords, you can simply tap the sign-in button with HUAWEI ID to log in your application easily and safely.
Setup:
1) Create a project in android studio.
2) Get the SHA-256 Key.
3) Create an app in the Huawei app gallery connect.
4) Enable account kit setting in Manage APIs Section.
5) Provide the SHA-256 Key in App Information Section.
6) Provide storage location.
7) Enable Huawei account under Auth Service in AGC.
{
"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"
}
8) After completing all the above points we need to download the agconnect-services.json from App Information Section. Place the json file in the app folder of the android project.
9) Enter the below maven URL inside the repositories of buildscript and allprojects respectively (project build.gradle file).
Code:
maven { url 'http://developer.huawei.com/repo/' }
10) Enter the below plugin in the app build.gradle file.
Code:
apply plugin: 'com.huawei.agconnect'
dependencies {
implementation 'com.huawei.hms:hwid:4.0.0.300'
11) Now Sync the gradle.
Implementation
1) In this app, we can implement Authorization code method.
Code:
HuaweiIdAuthParams authParams = new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setAuthorizationCode().createParams();
huaweiservice = HuaweiIdAuthManager.getService(MainActivity.this, authParams);
startActivityForResult(huaweiservice.getSignInIntent(), HUAWEI_SIGNIN);
 2) To Process the sign-in result after the authorization is complete.
Code:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == HUAWEI_SIGNIN) {
com.huawei.hmf.tasks.Task<AuthHuaweiId> authHuaweiIdTask = HuaweiIdAuthManager.parseAuthResultFromIntent(data);
if (authHuaweiIdTask.isSuccessful()) {
//The sign-in is successful, and the user's HUAWEI ID information and authorization code are obtained.
AuthHuaweiId huaweiAccount = authHuaweiIdTask.getResult();
Log.i(TAG, "Authorization code:" + huaweiAccount.getAuthorizationCode());
Log.d(TAG, "name: " + huaweiAccount.getDisplayName());
Log.d(TAG, "email: " + huaweiAccount.getEmail());
Log.d(TAG , "avatar : "+huaweiAccount.getAvatarUriString());
launchLoggedinActivity(huaweiAccount.getFamilyName() , huaweiAccount.getGivenName() , huaweiAccount.getAvatarUriString(),"huawei");
} else {
// The sign-in failed.
Log.e(TAG, "sign in failed : " + ((com.huawei.hms.common.ApiException) authHuaweiIdTask.getException()).getStatusCode());
}
}
}
3) To handle silent Sign-in
The authorization is required only for first registration with the HUAWEI ID. Then no approval is required for subsequent registrations with the same HUAWEI ID.
Code:
private void handleHuaweiSilentSignIn() {
HuaweiIdAuthParams authParams = new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM).createParams();
HuaweiIdAuthService service = HuaweiIdAuthManager.getService(MainActivity.this, authParams);
com.huawei.hmf.tasks.Task<AuthHuaweiId> task = service.silentSignIn();
task.addOnSuccessListener(new OnSuccessListener<AuthHuaweiId>() {
@Override
public void onSuccess(AuthHuaweiId authHuaweiId) {
// Obtain the user's HUAWEI ID information.
Log.i(TAG, "displayName:" + authHuaweiId.getDisplayName());
launchLoggedinActivity(authHuaweiId.getFamilyName() , authHuaweiId.getGivenName() , authHuaweiId.getAvatarUriString(),"huawei");
}
});
task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
// The sign-in failed. Try to sign in explicitly using getSignInIntent().
if (e instanceof ApiException) {
ApiException apiException = (ApiException)e;
Log.i(TAG, "sign failed status:" + apiException.getStatusCode());
}
}
});
}
4) To sign out from Huawei account.
Code:
Task<Void> signOutTask = service.signOut();
signOutTask.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
Log.i(TAG, "signOut complete");
}
});
5) To revoke authorization
Code:
service.cancelAuthorization().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
if (task.isSuccessful()) {
// Processing after a successful authorization revoking.
Log.i(TAG, "onSuccess: ");
} else {
// Handle the exception.
Exception exception = task.getException();
if (exception instanceof ApiException){
int statusCode = ((ApiException) exception).getStatusCode();
Log.i(TAG, "onFailure: " + statusCode);
}
}
}
Integrating Huawei Banner Ads
Ad kit service makes easy for developers to raise money with high-quality advertising from mobile devices. It maximizes the value of every impression by combining global advertiser demand, innovative ad formats, and advanced app monetization technology.
Showing ads to app users helps you to create a reliable revenue stream to help your company grow while concentrating on creating and improving quality apps. Advertisers can attract new consumers and users can discover related goods and services while enjoying free apps. So it is a win for developers, users, and advertisers.
In this app, we will integrate Huawei banner ad. It is a Rectangular advertising on the top or bottom of the screen show. When users interact with the app, banner ads remain on the screen and it can be refreshed periodically for a period of time.
Usecase
We will show banner ad at the bottom of flight search screen.
Implementation
1) Enter the below maven URL inside the repositories of buildscript and allprojects (project build.gradle file).
Code:
implementation 'com.huawei.hms:ads-lite:13.4.30.307'
2) To integrate Huawei banner ad, add BannerView in xml.
Code:
<RelativeLayout xmlns:hwads="http://schemas.android.com/apk/res-auto" >
<com.huawei.hms.ads.banner.BannerView
android:id="@+id/huawei_banner_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:visibility="gone"
hwads:adId="testw6vs28auh3"
hwads:bannerSize="BANNER_SIZE_360_57"/>
Note: We are using test ad ID. "testw6vs28auh3" is a dedicated test ad slot ID.
3) To show Banner Ad.
Code:
if(Utility.isDeviceHuaweiManufacturer() && Utility.isHuaweiMobileServicesAvailable(this)) {
hwBannerView = findViewById(R.id.huawei_banner_view);
hwBannerView.setVisibility(View.VISIBLE);
// Create an ad request to load an ad.
AdParam adParam = new AdParam.Builder().build();
hwBannerView.loadAd(adParam);
hwBannerView.setAdListener(adListener);
} private AdListener adListener = new AdListener() {
@Override
public void onAdLoaded() {
// Called when an ad is loaded successfully.
Log.d(TAG , "onAdLoaded");
}
@Override
public void onAdFailed(int errorCode) {
// Called when an ad fails to be loaded.
Log.d(TAG , "onAdFailed");
}
@Override
public void onAdOpened() {
// Called when an ad is opened.
Log.d(TAG , "onAdOpened");
}
@Override
public void onAdClicked() {
// Called when a user taps an ad.
Log.d(TAG , "onAdClicked");
}
@Override
public void onAdLeave() {
// Called when a user has left the app.
Log.d(TAG , "onAdLeave");
}
@Override
public void onAdClosed() {
// Called when an ad is closed.
Log.d(TAG , "onAdClosed");
}
};
Conclusion:
We have learnt how easy it is to integrate Huawei account and ads kit in the flight booking application.
Stay tune for next article to see more Huawei kit integration in flight booking app.
Links:
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/introduction-0000001050048870
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/publisher-service-introduction-0000001050064960
does huawei mobile services provide flight booking api?

Intermediate: Huawei Activity Identification Service | HMS location 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"
}
Introduction
Nowadays, everybody is using smartphones to do daily tasks like taking photos, looking up movie times, making calls etc. The best part of Android apps on mobile phones is that they are trying more and more to get to know their users. Many applications today take users' locations to provide users with locational feeds. One common example is a normal news app, where the app takes your current location and shows the news by location.
If you're a developer, you need to understand users better to give users a better experience of the application. You should know at any time what your users do. The more you know about your users, the better application for your users can build. For example, a distance calculator app lunches by itself when you start driving yourcar or bike and stops when you stop driving. Health and fitness app also uses this service to determine how many meters/kilometers you have covered on particular day.
What is Activity Identification Service?
Activity Identification Service does the heavy lifting using acceleration sensor, cellular network information and magnetometer from device to identify user’s current activity. Your app receives a list of detected activities, each of which includes possibility and identity properties.
The Activity Identification Service can detect following activities:
STILL: When the mobile device will be still, that is, the user is either sitting at someplace or the mobile device is having no motion, then the Activity Recognition Client will detect the STILL activity.
FOOT: When the mobile device is moving at a normal speed , that is, the user carrying the mobile device is either walking or running then the Activity Identification Service will detect the FOOT activity.
WALKING: This is a sub-activity of the FOOT activity which is detected by the Activity Identification Service when the user carrying the mobile device is walking.
RUNNING: This is also a sub-activity of FOOT activity which is detected by the Activity Recognition Client when the user carrying the mobile device is running.
VEHICLE: This activity detected when the mobile device is on the bus or car or some other kind of vehicle or the user holding the mobile device is present in the vehicle.
OTHERS: The Activity Identification service will show this result when the device is unable to detect any activity on the mobile device.
In this article, we will create a sample application to show user activity. When user clicks start button, we will identify user activity status along with possibility level and display the status in Textview and Imageview. And when user clicks on stop button, we will stop requesting activity identification updates.
Development Overview
Prerequisite
1. Must have a Huawei Developer Account.
2. Must have Android Studio 3.0 or later.
3. Must have Huawei phone running EMUI 5.0 or later.
4. EMUI 5.0 or later.
Software Requirements
1. Java SDK 1.7 or later.
2. Android 5.0 or later.
Preparation
1. Create an app or project in the Huawei App Gallery Connect.
2. Provide the SHA Key and App Package name of the project in App Information Section and enable the Location Kit API.
3. Download the agconnect-services.json file.
4. Create an Android project.
Integration
1. Add below to build.gradle (project) file under buildscript/repositories and allprojects/repositories.
Code:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
dependencies {
classpath "com.android.tools.build:gradle:4.0.1"
classpath 'com.huawei.agconnect:agcp:1.4.2.300'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
2. Add below to build.gradle (app) file, under dependencies to use the Location kit SDK.
Code:
apply plugin: 'com.huawei.agconnect'
dependencies {
implementation 'com.huawei.hms:location:5.0.5.300'
}
Tip: Minimum android version supported for these kits is 19.
3. Add below permissions to manifest file.
For version earlier than android Q
Code:
<uses-permission android:name="com.huawei.hms.permission.ACTIVITY_RECOGNITION"/>
For version Android Q and later
Code:
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
Note: The above permissions are dangerous permission and need to be requested dynamically. Requesting permission dynamically is not covered in this article.
Development
We need to register static broadcast receiver in AndroidManifest.xmlto listen to activity status update identified by Activity Identification Service.
Code:
<receiver
android:name=".LocationReceiver"
android:exported="true">
<intent-filter>
<action android:name="com.huawei.hmssample.location.LocationBroadcastReceiver.ACTION_PROCESS_LOCATION" />
</intent-filter>
</receiver>
Now the next step is to add the UI for our Main Activity. In our application, we will be having one TextView to display the name of the current activity and display corresponding image on ImageView and one TextView to display the possibility of Activity. We will have two Buttons to start and stop activity identification tracking. So, the activity_main.xml file looks something like this:
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"
android:background="#FAF0E6"
tools:context=".MainActivity">
<ImageView
android:id="@+id/ivDisplay"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_centerInParent="true"
android:scaleType="centerInside"
android:src="@drawable/ic_still" />
<TextView
android:id="@+id/tvidentity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/ivDisplay"
android:layout_marginTop="5dp"
android:textStyle="bold"
android:textColor="#192841"
android:textSize="25sp"
android:layout_centerHorizontal="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/tvpossiblity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/tvidentity"
android:textSize="20sp"
android:textColor="#192841"
android:layout_centerHorizontal="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/bStart"
android:layout_weight="1"
android:layout_margin="5dp"
android:text="Start Tracking"
android:textColor="@color/upsdk_white"
android:background="#192841"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/bStop"
android:layout_margin="5dp"
android:layout_weight="1"
android:text="Stop Tracking"
android:textColor="@color/upsdk_white"
android:background="#192841"/>
</LinearLayout>
</RelativeLayout>
Now let’s create instance of ActivityIdentificationService in onCreate() method of MainActivity.java
Java:
private PendingIntent mPendingIntent;
private ActivityIdentificationService identificationService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); intializeTracker(); }
private void intializeTracker() {
identificationService = ActivityIdentification.getService(this);
mPendingIntent = obtainPendingIntent();
}
To obtain PendingIntent object
Java:
private PendingIntent obtainPendingIntent() {
Intent intent = new Intent(this, LocationReceiver.class);
intent.setAction(LocationReceiver.ACTION_NAME);
return PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
When user clicks on Start Tracking Button, we will request activity identification updates by calling createActivityIdentificationUpdates() method.
identificationService.createActivityIdentificationUpdates(5000, mPendingIntent)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@override
public void onSuccess(Void aVoid) {
Log.i(TAG, "createActivityIdentificationUpdates onSuccess");
}
})
// Define callback for request failure.
.addOnFailureListener(new OnFailureListener() {
@override
public void onFailure(Exception e) {
Log.e(TAG, "createActivityIdentificationUpdates onFailure:" + e.getMessage());
}
});
This method has two parameters: detectionIntervalMillis and pendingIntent, which indicate the detection interval (in milliseconds) and action to perform, respectively.
On click of Stop Tracking Button, we will stop activity identification updates.
Java:
identificationService.deleteActivityIdentificationUpdates(mPendingIntent)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.i(TAG, "deleteActivityIdentificationUpdates onSuccess");
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.e(TAG, "deleteActivityIdentificationUpdates onFailure:" + e.getMessage());
}
});
Finally, We can get activity identification result (containing identity and possibility) from intent received by the broadcast receiver.
Java:
public class LocationReceiver extends BroadcastReceiver {
public static final String ACTION_NAME = "com.huawei.hms.location.ACTION_PROCESS_LOCATION";
@Override
public void onReceive(Context context, Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_NAME.equals(action)) {
// Obtains ActivityIdentificationResponse from extras of the intent sent by the activity identification service.
ActivityIdentificationResponse activityIdentificationResponse = ActivityIdentificationResponse.getDataFromIntent(intent);
if(activityIdentificationResponse!= null) {
List<ActivityIdentificationData> list = activityIdentificationResponse.getActivityIdentificationDatas();
ActivityIdentificationData identificationData = list.get(list.size() -1);
int identificationIdentity = identificationData.getIdentificationActivity();
int possibility = identificationData.getPossibility();
Intent i = new Intent("activityIdentificationReceiver");
i.putExtra("identity", identificationIdentity);
i.putExtra("possibility", possibility);
context.sendBroadcast(i);
}
}
}
}
}
getActivityIdentificationDatas() API is used to obtain the list of activitiy identification list. The activity identifications are sorted by most probable activity first.
We have created Utils.java class to obtain activity status from identity code obtained from LocationReceiver
Java:
public class Utils {
public static String getActivityIdentityName(int code) {
switch(code) {
case ActivityIdentificationData.VEHICLE:
return "VEHICLE";
case ActivityIdentificationData.BIKE:
return "BIKE";
case ActivityIdentificationData.FOOT:
return "FOOT";
case ActivityIdentificationData.STILL:
return "STILL";
case ActivityIdentificationData.OTHERS:
return "OTHERS";
case ActivityIdentificationData.WALKING:
return "WALKING";
case ActivityIdentificationData.RUNNING:
return "RUNNING";
default:
return "No Data Available";
}
}
public static int getActivityIdentityDrawableID(int code) {
switch(code) {
case ActivityIdentificationData.VEHICLE:
return R.drawable.ic_driving;
case ActivityIdentificationData.BIKE:
return R.drawable.ic_on_bicycle;
case ActivityIdentificationData.FOOT:
return R.drawable.ic_still;
case ActivityIdentificationData.STILL:
return R.drawable.ic_still;
case ActivityIdentificationData.OTHERS:
return R.drawable.ic_unknown;
case ActivityIdentificationData.WALKING:
return R.drawable.ic_walking;
case ActivityIdentificationData.RUNNING:
return R.drawable.ic_running;
default:
return R.drawable.ic_unknown;
}
}
}
Code snippet of MainActivity.java
Java:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private ActivityConversionRequest request;
private Button bStart, bStop;
private TextView tvPossiblity, tvIdentity;
private ImageView ivDisplay;
private PendingIntent mPendingIntent;
private ActivityIdentificationService identificationService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intializeTracker();
bStart = findViewById(R.id.bStart);
bStop = findViewById(R.id.bStop);
tvIdentity = findViewById(R.id.tvidentity);
tvPossiblity = findViewById(R.id.tvpossiblity);
ivDisplay = findViewById(R.id.ivDisplay);
bStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
identificationService.createActivityIdentificationUpdates(5000, mPendingIntent)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.i(TAG, "createActivityIdentificationUpdates onSuccess");
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.e(TAG, "createActivityIdentificationUpdates onFailure:" + e.getMessage());
}
});
}
});
bStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
identificationService.deleteActivityIdentificationUpdates(mPendingIntent)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.i(TAG, "deleteActivityIdentificationUpdates onSuccess");
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Log.e(TAG, "deleteActivityIdentificationUpdates onFailure:" + e.getMessage());
}
});
}
});
}
private void intializeTracker() {
identificationService = ActivityIdentification.getService(this);
mPendingIntent = obtainPendingIntent();
}
// Get PendingIntent associated with the custom static broadcast class LocationBroadcastReceiver.
private PendingIntent obtainPendingIntent() {
Intent intent = new Intent(this, LocationReceiver.class);
intent.setAction(LocationReceiver.ACTION_NAME);
return PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
@Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("activityIdentificationReceiver");
registerReceiver(mIdentificationReceiver , filter);
}
@Override
protected void onPause() {
super.onPause();
try {
if(mIdentificationReceiver != null){
unregisterReceiver(mIdentificationReceiver);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private BroadcastReceiver mIdentificationReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
int possibility = intent.getIntExtra("possibility", 0);
int identity = intent.getIntExtra("identity", 103);
tvIdentity.setText(Utils.getActivityIdentityName(identity));
tvPossiblity.setText("Possibility : " + String.valueOf(possibility));
ivDisplay.setImageResource(Utils.getActivityIdentityDrawableID(identity));
}
};
}
Tips and Tricks
1.During writing of this article, the activity identification service cannot identify the cycling and riding activities on devices outside the Chinese mainland.
2. ACTIVITY_RECOGNITION is dangerous permission and should be requested dynamically.
Conclusion
In this article, we have learnt how to use the Activity Identification Service in our application to determine the activities that users are doing at any given time. The Activity Identification Service determines the ongoing activities based on a possibility value that tells you which activity is currently taking place.
Hope you found this story useful and interesting.
Happy coding!
References
https://developer.huawei.com/consum...troduction-0000001050706106-V5?ha_source=hms1

Real-time Locating Helps Users Get Around

Real-time locating is a core function for many apps, allowing them to quickly and accurately locate users' real time locations.
HUAWEI Location Kit enables apps to quickly obtain precise user locations and build up global locating capabilities, helping you implement personalized map display and interaction, as well as improve overall location-based service experience.
This article demonstrates how to use HUAWEI Location Kit and Map Kit to implement the real-time locating capability in an app.
Expectations​An app can obtain and display a user's real-time location on the map, especially when the app is launched for the first time. The map display changes in accordance to the user's actual location.
{
"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"
}
Involved Capabilities​Location Kit: basic locating
Map Kit: map display
Implementation Principle​An app uses Location Kit to obtain a user's real-time location and uses Map Kit to display the My Location button on the in-app map that the user can tap to determine their real-time location.
Preparations​Register as a developer and create a project in AppGallery Connect.
Click here to register as a developer.
Create an app, add the SHA-256 signing certificate fingerprint, enable Map Kit and Site Kit, and download the agconnect-services.json file of the app. For detailed instructions, please visit the official website of HUAWEI Developers.
Configure the Android Studio project.
Copy the agconnect-services.json file to the app directory of the project.
Go to allprojects > repositories and configure the Maven repository address for the HMS Core SDK.
Go to buildscript > repositories and configure the Maven repository address for the HMS Core SDK.
If the agconnect-services.json file has been added to the app, go to buildscript > dependencies and add the AppGallery Connect plugin configuration.
Code:
buildscript {
repositories {
maven { url 'https://developer.huawei.com/repo/' }
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.3.2'
classpath 'com.huawei.agconnect:agcp:1.3.1.300'
}
}
allprojects {
repositories {
maven { url 'https://developer.huawei.com/repo/' }
google()
jcenter()
}
}
Add build dependencies in the dependencies block.
Code:
dependencies {
implementation 'com.huawei.hms:maps:{version}'
implementation 'com.huawei.hms:location:{version}'
}
Add the following configuration to the file header.
Code:
apply plugin: 'com.huawei.agconnect'
Copy the signing certificate generated in Generating a Signing Certificate to the app directory of your project, and configure the signing certificate in android in the build.gradle file.
Code:
signingConfigs {
release {
// Signing certificate.
storeFile file("**.**")
// KeyStore password.
storePassword "******"
// Key alias.
keyAlias "******"
// Key password.
keyPassword "******"
v2SigningEnabled true
v2SigningEnabled true
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
debuggable true
}
debug {
debuggable true
}
}
Key Code Implementation​(1) Compile a service to obtain a user's real-time location.
Java:
public class LocationService extends Service {
private final String TAG = this.getClass().getSimpleName();
List<ILocationChangedLister> locationChangedList = new ArrayList<>();
// Location
private FusedLocationProviderClient fusedLocationProviderClient;
private LocationRequest mLocationRequest;
private final LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
locationResult.getLocations();
Log.d(TAG, "onLocationResult: " + locationResult);
Location location = locationResult.getLocations().get(0);
Log.w(TAG, "onLocationResult:Latitude " + location.getLatitude());
Log.w(TAG, "onLocationResult:Longitude " + location.getLongitude());
for (ILocationChangedLister locationChanged : locationChangedList) {
locationChanged.locationChanged(new LatLng(location.getLatitude(), location.getLongitude()));
}
}
@Override
public void onLocationAvailability(LocationAvailability locationAvailability) {
super.onLocationAvailability(locationAvailability);
Log.d(TAG, "onLocationAvailability: " + locationAvailability.toString());
}
};
private final MyBinder binder = new MyBinder();
private final Random generator = new Random();
@Nullable
@Override
public IBinder onBind(Intent intent) {
return binder;
}
@Override
public void onCreate() {
Log.i("DemoLog", "TestService -> onCreate, Thread: " + Thread.currentThread().getName());
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("DemoLog",
"TestService -> onStartCommand, startId: " + startId + ", Thread: " + Thread.currentThread().getName());
return START_NOT_STICKY;
}
@Override
public boolean onUnbind(Intent intent) {
Log.i("DemoLog", "TestService -> onUnbind, from:" + intent.getStringExtra("from"));
return false;
}
@Override
public void onDestroy() {
Log.i("DemoLog", "TestService -> onDestroy, Thread: " + Thread.currentThread().getName());
super.onDestroy();
}
public int getRandomNumber() {
return generator.nextInt();
}
public void addLocationChangedlister(ILocationChangedLister iLocationChangedLister) {
locationChangedList.add(iLocationChangedLister);
}
public void getMyLoction() {
Log.d(TAG, "getMyLoction: ");
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
SettingsClient settingsClient = LocationServices.getSettingsClient(this);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
mLocationRequest = new LocationRequest();
builder.addLocationRequest(mLocationRequest);
LocationSettingsRequest locationSettingsRequest = builder.build();
// Location setting
settingsClient.checkLocationSettings(locationSettingsRequest)
.addOnSuccessListener(locationSettingsResponse -> fusedLocationProviderClient
.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.getMainLooper())
.addOnSuccessListener(aVoid -> Log.d(TAG, "onSuccess: " + aVoid)))
.addOnFailureListener(Throwable::printStackTrace);
}
public class MyBinder extends Binder {
public LocationService getService() {
return LocationService.this;
}
}
public interface ILocationChangedLister {
/**
* Update the location information
*
* @param latLng The new location information
*/
public void locationChanged(LatLng latLng);
}
}
(2) Add a map in the activity to monitor a user's real-time location.
Add a map using the XML layout file:
XML:
<com.huawei.hms.maps.MapView
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Add a map in the activity:
XML:
mapView.onCreate(null);
mapView.getMapAsync(this);
Tap My Location button to display the current location on the map:
XML:
@Override
public void onMapReady(HuaweiMap huaweiMap) {
hMap = huaweiMap;
hMap.setMyLocationEnabled(true);
}
Bind Location Kit to listen to location changing events:
private ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
isBound = true;
if (binder instanceof LocationService.MyBinder) {
LocationService.MyBinder myBinder = (LocationService.MyBinder) binder;
locationService = myBinder.getService();
Log.i(TAG, "ActivityA onServiceConnected");
locationService.addLocationChangedlister(iLocationChangedLister);
locationService.getMyLoction();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
isBound = false;
locationService = null;
Log.i(TAG, "ActivityA onServiceDisconnected");
}
};
Bind the activity to LocationService:
private void bindLocationService() {
Intent intent = new Intent(mActivity, LocationService.class);
intent.putExtra("from", "ActivityA");
Log.i(TAG, "-------------------------------------------------------------");
Log.i(TAG, "bindService to ActivityA");
mActivity.bindService(intent, conn, Context.BIND_AUTO_CREATE);
}
Process the location changing events in the location changing listener:
LocationService.ILocationChangedLister iLocationChangedLister = new LocationService.ILocationChangedLister() {
@Override
public void locationChanged(LatLng latLng) {
Log.d(TAG, "locationChanged: " + latLng.latitude);
Log.d(TAG, "locationChanged: " + latLng.longitude);
updateLocation(latLng);
}
};
Update map view:
private void updateLocation(LatLng latLng) {
mLatLng = latLng;
hMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 1));
}
Testing the App​You can use a mock location app to change your current location and see how the map view and My Location button alter accordingly.
To learn more, please visit:
HUAWEI Developers official website
Development Guide
Reddit to join developer discussions
GitHub or Gitee to download the demo and sample code
Stack Overflow to solve integration problems
Follow our official account for the latest HMS Core-related news and updates.
Original Source

Categories

Resources