How do I integrate HMS to my game using HMS Unity Plugin 2.0? — Part 4 - 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​Before I begin, if you are not coming to this article from part 3 of the article, you can read here. For part 2 of the series, you can read here. If you have not seen part 1 either, you can click here. This is the fourth part of our HMS Unity Plugin 2.0 integration guide. This time I will be talking about other features of GameService: Leaderboards and SaveGame.
Normally, this part of the series was not planned, however, I thought that developers who might be interested in the other two parts of the GameService may be left off without a guide. Thus, I am adding this 4th part. I will be using a different game than the other three, but, I will try to be as helpful and as guiding as I can in this article as well, so you can adjust these two features to wherever you want to.
Small Warning Before We Proceed​I will show the AGC side steps as much as I can, but this article also assumes that you have completed the part 1 app/project creation etc. and have an app running in contact with AGC and the plugin is ready to use. (You can just enable Banner Ads and tick test ads to test if the plugin is working.) Also, for the tests, make sure your account is registered as a sandbox test account. Details can be found in the docs link, if you have not done it yet.
My Game​
As I said, I am using a different game for this part, but again a very simple hyper-casual one. You have a rock and 5 rock counts at the beginning of the game. You throw it in a projected trajectory to hit the balloons and you score points. Since the balloon generation and speed are determined at random, it is not as easy as it looks but it has a very simple logic. Its name is “Hit The Target”.
GameService — Leaderboards​Leaderboards let you create leaderboards in your game so that the players can compete and see how they rank in comparison to others. Huawei, like achievements, has its own UI to help you up setting up the leaderboard system. All you have to do is to make sure that GameService is enabled in AppGallery Connect (aka AGC), then create a leaderboard with some pre-defined rules and use the plugins easy-to-use managers to send/submit scores to leaderboards. It literally takes one line to submit the score in simple scenarios after the AGC is set up, thanks to HMS Unity Plugin 2.0.x.
AGC Side​You need to sign in to AGC and go to My apps. Then choose your app. My app in this case is “Hit The Target”. Go from “Distribute” tab to “Operate” tab and choose “Leaderboards”. Then click “New” button. You should see the screen below.
Add the details of your leaderboard. What kind of scores you want, how the formatting should be, min/max numbers that can be submitted etc. are all can be edited here. When you are done, click “Save”.
Now, we need to copy the ID of the leaderboard, so we can feed it to the plugin and use it in our game.
Do not release the leaderboards. Click “Obtain Resources” and copy the ID of the leaderboard you just created.
Unity Side​Now head to Unity. Open the drop-down Huawei menu, click Kit Settings. Enable GameService (Account Kit will automatically be enabled and it is okay.) and go to the GameService tab.
Add a name to your leaderboard (which I used the same long name that I used in AGC) and paste the ID you copied in the previous step. Then, click create constant classes. Make sure to check the “Initialize On Start” button, or else you will have to write additional code.
Coding Phase​The coding phase in Leaderboards is very easy. All you have to do is to submit the score to the leaderboard you have created.
Code:
HMSLeaderboardManager.Instance.SubmitScore(HMSLeaderboardConstants.HitTheTargetGeneralLeaderboard, GameManager.score /*score you want to submit*/);
You use the instance of HMSLeaderboardManager as usual and just call SubmitScore() function. Use the constant class that is automatically generated by the plugin to get which leaderboard you want to submit and enter the score type as the second parameter.
That's it for submitting the score, you should see it in the leaderboards and in the AGC.
One thing left for the integration. You should allow your users to see the leaderboard UI done by Huawei and check which leaderboards are there and which scores are submitted. This will help with the competitiveness of the game.
For that, all you need to do is to call again a one-liner code thanks to the plugin.
Code:
HMSLeaderboardManager.Instance.ShowLeaderboards();
I use this line inside a function and call that function in a UI Button onClick. Thus, whenever users click on the button, they are directed to the leaderboard UI and check which leaderboards are present. It should look like below.
GameService — SaveGame​SaveGame takes more time than usual because of its very nature and purpose but it is a very powerful tool. As the name suggests, this kit helps you save the game progress of the player to the Huawei Cloud and lets the players load the saved progress to the current game. By this way, users never lose progress. It has its own UI to show saved games but it is also possible to implement your own UI, if you wish to do so.
You may save and load the game progress automatically in the background and set up a load-on-prompt system, or, like I would do it, save and load by the user’s actions. It is totally up to and to your game.
In my game, since it is a very simple game, I save the progress (score) and the rockCount and let the user save whenever s/he wishes. Later, the user can load this progress anytime in the pause menu and keep playing from that saved game. I will use the default Huawei UI, but if you wish to implement your own UI, I will leave links to docs where it talks about custom UI in the reference section. Make sure you check out that link, or alternatively, click here. I will talk about the code details later. First, let’s solve some error codes that you may possibly bump into.
Error Code 7219 in HMS GameService and Its Solution​
If you have started the development already, you might have gotten the error 7219 in GameService SaveGame implementation and wonder why that could arise. It is because you need to agree to the user agreement in Drive Kit by Huawei located in https://cloud.huawei.com/ to be able to use SaveGame feature. The reason is that SaveGame saves the game files to the cloud using Drive Kit and if that agreement is not signed by your developer account, you will receive an error called 7219 and will not be able to proceed/test your code. Make sure you click the link, sign in, and agree to it. This is suggested before you start the implementation.
Coding Phase​Before going into actual coding, let me mention this first. To let the users see the saved games in default UI and load the games with simple clicks, call the one-liner function below. (just like leaderboards) It will open the UI provided by AppGallery.
Code:
HMSSaveGameManager.Instance.ShowArchive();
Make sure you assign this code as an onClick to a UI button, or implement your own logic to access that UI.
Now, for the SaveGame we follow this doc, but on a Unity setting with the plugin. The order will not change but to see how you should code, bear with me. I will share the full new class in my game and explain/break down the code later. You do not have to open the docs, I will share the steps with you below, but always keep this doc in mind for the latest updates.
What needs to be done:​The order in the official doc (written in Java):
Request DRIVE_DATA permission from the user and get ArchivesClient() object.
Get maxThumbnailSize and detailSize from the SDK. These must be requested, although you may not need them in your code.
Determine the details to save (your own parameters to save) and create ArchiveDetails object.
Write the archive metadata (such as the archive description, progress, and cover image) to the ArchiveSummaryUpdate object.
Call addArchive() method to save the game to the drive.
Notes:
You do not need to request a user permission in Unity side thanks to the plugin. It will be handled automatically.
Others will be talked about in detail below on a simple game I mentioned. If you have more complicated cases that cannot be adjusted, please refer to official documentation.
Coding in C#​Let me share the code first.
Code:
using UnityEngine;
using HmsPlugin;
using HuaweiMobileServices.Game;
using System.Text;
public class ManagerOfSaveGame : MonoBehaviour
{
// Start is called before the first frame update
int maxThumbnailSize;
int detailSize;
GameStarterScript gameStarterScript;
void Start()
{
gameStarterScript = GameObject.Find("PauseButton").GetComponent<GameStarterScript>();
//HMSSaveGameManager.Instance.GetArchivesClient().LimitThumbnailSize.AddOnSuccessListener((x) => { });
HMSSaveGameManager.Instance.GetArchivesClient().LimitThumbnailSize.AddOnSuccessListener(LimitThumbnailSizeSuccess);
HMSSaveGameManager.Instance.GetArchivesClient().LimitDetailsSize.AddOnSuccessListener(LimitDetailSizeSuccess);
HMSSaveGameManager.Instance.SelectedAction = SelectedActionCreator;
HMSSaveGameManager.Instance.AddAction = AddActionCreator;
}
private void LimitDetailSizeSuccess(int thumbnailSize)
{
maxThumbnailSize = thumbnailSize;
}
private void LimitThumbnailSizeSuccess(int returnedDetailSize)
{
detailSize = returnedDetailSize;
}
private void SelectedActionCreator(ArchiveSummary archiveSummary)
{
//load your game
Debug.Log("YOU ENTERED SELECTED ACTION CALLBACK!");
long score = archiveSummary.CurrentProgress;
long rockCount = archiveSummary.ActiveTime;
if (GameManager.rockCount <= 0)
{
gameStarterScript.PlayGameWithParameters((int)score, (int)rockCount);
}
else
{
Debug.Log("Cannot load a finished game");
}
//start the game but change the parameters to load.
}
private void AddActionCreator(bool obj)
{
if(GameManager.rockCount != 0)
{
//save your game
string description = "Rock:" + GameManager.rockCount + " Score:" + GameManager.score;
long playedTime = GameManager.rockCount; //rock count
long progress = GameManager.score;
ArchiveDetails archiveContents = new ArchiveDetails.Builder().Build();
archiveContents.Set(Encoding.ASCII.GetBytes(progress + description + playedTime));
ArchiveSummaryUpdate archiveSummaryUpdate =
new ArchiveSummaryUpdate.Builder()
.SetActiveTime(playedTime)
.SetCurrentProgress(progress)
.SetDescInfo(description)
//.SetThumbnail(bitmap)
//.SetThumbnailMimeType(imageType)
.Build();
HMSSaveGameManager.Instance.GetArchivesClient().AddArchive(archiveContents, archiveSummaryUpdate, true).AddOnSuccessListener((archiveSummary) => {
string fileName = archiveSummary.FileName;
string archiveId = archiveSummary.Id;
//if you wanna use these you can. But this just indicates that it is successfully saved.
print("fileName is: " + fileName + " and archiveId is " + archiveId);
print("GamePlayer is: " + archiveSummary.GamePlayer + " and GameSummary is " + archiveSummary.GameSummary);
print("CurrentProgress is: " + archiveSummary.CurrentProgress + " and ActiveTime is " + archiveSummary.ActiveTime);
}).AddOnFailureListener((exception) => {
print("statusCode:" + exception.GetBaseException());
});
}
else
{
print("Game is over. Cannot save a finished game!");
}
}
}
Let's break down the code to understand.
First, I created a separate function called ManagerOfSaveGame.cs to manage SaveGames. I also create a game object in my scene and put the script in it. It has no appearance in the scene to the user. This is just to control it.
In the Start() function, I get the methods to request the parameters because documentation lists them as first thing to do. I will not use them later, so I just get the parameters and be done with it.
Then I create the corresponding functions in my script to SelectedAction and AddAction fields. First is to load the game from UI on click and the second is to save the game to the drive.
AddAction (Save your game)​If I were you, I would copy the contents of the shown function and paste it to my game. Then, I would alter the parameters I want to alter. I first put an if check to see if the game is over. Since my game is a simple throw game and my rock count goes from 5 to 0, 0 rock count means a finished game. Although I could, I do not allow my users to save their games if they are already done because my UI technically allows users to access save game screen after the game is over.
You have several parameters that you can adjust. My code above follows the documentation order so you can be sure of that. What you should do with your game is to determine a description of the save games, a progress indicator, and if needed, the active time. I keep my score in score parameter and my rock count in active time parameter. Normally, I do not use time related functions but since the parameters that one can save is limited, I decided to use active time as an in-game save functionality. You can also do the same if you need. Typically, you can keep the level information, score information etc. in the progress “long” type parameter, and retrieve it when loading the game.
Rest goes according to “rules”. You can take them as is and adjust where needed. I do not use a Bitmap or an image to save with my save files. You can alternatively take a screenshot of the save moment and save it with the current progress. Huawei SDK allows that too, but I do not need it in my game.
Then you call AddArchive method as shown and success callback indicates that the game is saved. You need need to do anything with return parameter but I showed how to retrieve values nonetheless, if anyone ever needs it.
You can also get the exception message if the game cannot be saved for some reason.
SelectedAction (Load your game)​This function will be automatically called when the users click on a previously saved game in default Huawei UI. Thus, what you need to do is to retrieve the values that you saved while saving the game and load the game according to your game logic.
For my case, I retrieve the rock count and score as shown, then start my scene with these parameter. They are set as static, so I can alter them easily.
You can adjust here depending on your game logic and how you want to load your game when the user clicks it. For example, if you kept the level information in progress parameter, then you try reloading that Unity scene to start that level from scratch.
Tips and Tricks​
Do not publish the leaderboards if you want to keep testing them. Unless you are done with testing and want to publish your app in AppGallery, it should always be left as in Testable mod and releasing it will hinder your testing efforts.
Custom UI can be programmed, although Huawei already provides a UI for Leaderboards and SaveGames (for Achievements too!). Please refer to docs below in references to see the details.
When loading your game, beware that progress parameter is called “CurrentProgress”. If you called it something else, like I called just “progress”, make sure you retrieve the “CurrentProgress” field because there is no such field called “progress”.
Conclusion​That's it! You have successfully integrated Leaderboards and SaveGame features. They have a wide variety of use cases and I know that mine are simple; but at least, I believe, I gave you the insight so that you can adapt these kits to your game and draw more users.
I hope that this article series has been helpful for you. You can always ask questions below, if you have anything unanswered in your mind.
Good luck on the store and see you in my other articles!
References​
HMS Unity Plugin 2.0 Branch (Github Page)
GameService Result Codes Page
SaveGame Docs
Leaderboard Docs
Documentation of every kit in Huawei Docs (Links are present in the GitHub readme)
Original Source

Related

Confused about how to evolve from (very) basic Android Development

Hello.
I followed all the New Boston Android videos, did everything, understood everything.
I tried to create a basic RSS feed reader, in order to better incorporate some concepts I learned in the New Boston videos (http processing, xml processing, adapting the content to lists, custom lists, etc). When I got to pass the information from the http processed data to xml parser and the list, that's when I got too much confused and knew I didn't have enough knowledge.
Then I tried to do some "Shopping List Manager" (just like OI Shopping, a bit adapted more to my taste), in order to learn.
However, again, when I neededto pass information to other objects in other classes or something like that, I get confused and don't know what to do.
So I bought CommonsWare book, "The Busy Coder's Guide to Android", which I have the latest version (5.1) and I'm reading, but I don't like to advance when I don't fully understand something. This time I'm stuck on the Action Bar part, more precisely this one:
Code:
private void configureActionItem(Menu menu) {
EditText add=
(EditText)menu.findItem(R.id.add).getActionView()
.findViewById(R.id.title);
add.setOnEditorActionListener(this);
}
I know this will seem very basic to many of you, but I get really confused on all this calls, returning results and more calls.
I don't have a background on OOP, except when I worked with PHP frameworks like Symfony, I work usually with direct task programming (scripting, automation, etc), as I am a Linux System Administrator, so my code is mainly scripting and web interface building (Python, Shell Script, PHP, Javascript, etc).
Can anybody explain what can I do to better understand this? It's just lack of practice and in time I'll understand better? Is it OOP lack of knowledge/practice? Or is it Java lack of knowledge/practice?
Thanks a lot for all your help.
Maybe the best approach is to get some face time with a person who is more experienced and have him explain to you the concept you have trouble with while focusing on the parts you don't grasp. A real human has this flexibility to do a "targeted strike" unlike a tutorial or a book that has no idea where in particular the student may get confused.
For this particular issue, the issue can be summarized as follows. Let's say you have an object call a function:
Code:
orange.peel();
This should be relatively straightforward. The next level of complexity is the fact that obj is just a variable representing an object, and in fact we can substitute anything else that evaluates to an object (i.e.: after it runs, you end up with an object). For example these all are legal ways to call the method as long as types match:
Code:
(new Orange()).peel();
(shouldEatSmallerOrange ? smallerOrange : largerOrange).peel();
retrieveOrangeFromBox().peel();
The last line illustrates calling some other function that returns the object, which is then used to call a second function. The final step from here is to recognize that instead of a single retrieveOrangeFromBox() we can have a chain of functions, each of which returns an object that is used to call the next function in line. For example:
Code:
findCar().accessCarTrunk().unloadBoxFromTrunk().retrieveOrangeFromBox().peel();
The names are unnecessarily verbose to illustrate how functions and their results relate to each other.
OOP + Android system
You're not that clear as to exactly what you are having a problem with, but in general, it sounds like you need to get a java book and learn the basic concepts of classes and interfaces. Since you say you have a background in PHP you could probably go pretty far just by following the Java tutorials on the Sun website. I say java because that's the target language here, any book on OOP in any language would be adequate but learning java would give you the added ability to read other people's android code examples more easily.
After that, you can learn the Android framework. You develop in the Java language but you work within the android framework. What that means is that here, for example, the action bar is provided to you by the android system, and this callback is called by the system, so it is all set up for you. But to understand what is happening, you need to understand when the system calls this method and what it does. That is the framework.
So more specifically, how can you understand this code? This method is called from another method, onCreateOptionsMenu(). OnCreateOptionsMenu() is a method in the Activity class that is called automatically by the system at a specific time. You need to read about the Activity class and the Activity lifecycle on the android developers site. If you want your activity to provide an options menu, you create it in OnCreateOptionsMenu and return it, the system will handle it from there. So back to configureActionItem(Menu menu), here you are passing in the menu object, which contains MenuItem objects, which the system uses to populate the menu (either on the action bar, or when you hit the menu button, depending on the android version). Each MenuItem object has a view that is associated with it (usually created in an XML file).
One thing that may be hard to understand is that all these calls are chained, so if you don't know what they are returning you don't know where to look for help. It's easier if you separate the calls out. Here, the documentation is your friend. If you look at the Menu class on the android dev site, you see that findItem() returns a MenuItem. So then you look up MenuItem, and you see that getActionView() returns a View. Look at the View class, and you can see findViewById() returns another view (a sub-view that is contained within this view). so when you look at it all together, unchained:
Code:
private void configureActionItem(Menu menu) {
MenuItem mi = menu.findItem(R.id.add);
View parentView = mi.getActionView();
EditText add = (EditText)parentView.findViewById(R.id.title);
}
findViewById returns a View, but you know that the view known by the id R.id.title is an EditText view, and you want to use it as an EditText, so you have to cast the View to an EditText (which is a subclass of View) so that the compiler knows that it is an EditText type of view. That's what the (EditText) is doing in front of the findViewById call. To understand that you need to read about subclassing and strongly-typed programming languages. PHP is weakly-typed, so that might be new to you.
finally, you call setOnEditActionListener on the EditText. OnEditActionListener is an interface that you have implemented in this class. An interface defines a common set of methods that are guaranteed to be present in whichever class has implemented it. So when you set the OnEditActionListener to this, (this means the current instance of this class), the EditText will hold on to the "this" object and it knows that it can call a certain set of methods on it. What are those methods? look up the OnEditActionListener interface in the docs:
it only has one method,
Code:
public abstract boolean onEditorAction (TextView v, int actionId, KeyEvent event);
so somewhere in this class, you will have this method defined and this is where you put code that you want to run when the EditText triggers this action. I assume this get called when the user touches the EditText.
It's really not going to be easy to work with android if you don't have a basic knowledge of OOP, specifically classes, inheritance, and interfaces. Also, knowing how java implements these concepts will help a lot. Then you can use your book to learn the Android framework.
GreenTuxer said:
Hello.
I followed all the New Boston Android videos, did everything, understood everything.
I tried to create a basic RSS feed reader, in order to better incorporate some concepts I learned in the New Boston videos (http processing, xml processing, adapting the content to lists, custom lists, etc). When I got to pass the information from the http processed data to xml parser and the list, that's when I got too much confused and knew I didn't have enough knowledge.
Then I tried to do some "Shopping List Manager" (just like OI Shopping, a bit adapted more to my taste), in order to learn.
However, again, when I neededto pass information to other objects in other classes or something like that, I get confused and don't know what to do.
So I bought CommonsWare book, "The Busy Coder's Guide to Android", which I have the latest version (5.1) and I'm reading, but I don't like to advance when I don't fully understand something. This time I'm stuck on the Action Bar part, more precisely this one:
Code:
private void configureActionItem(Menu menu) {
EditText add=
(EditText)menu.findItem(R.id.add).getActionView()
.findViewById(R.id.title);
add.setOnEditorActionListener(this);
}
I know this will seem very basic to many of you, but I get really confused on all this calls, returning results and more calls.
I don't have a background on OOP, except when I worked with PHP frameworks like Symfony, I work usually with direct task programming (scripting, automation, etc), as I am a Linux System Administrator, so my code is mainly scripting and web interface building (Python, Shell Script, PHP, Javascript, etc).
Can anybody explain what can I do to better understand this? It's just lack of practice and in time I'll understand better? Is it OOP lack of knowledge/practice? Or is it Java lack of knowledge/practice?
Thanks a lot for all your help.
Click to expand...
Click to collapse
Thanks a lot for your help. I also think my issue is with OOP, but I needed the opinion of people with more knowledge.
I understand very well what you said about onCreateOptionsMenu(), why and when is called, Activity class, lifecycle, etc.
Those things I understand without any problem. I also understand the basics of OOP, but I don't know almost nothing about Interfaces and I don't have almost any experience with inheritance, although I understand it.
I think I'm just confused because I haven't worked very long with OOP. I just don't know if I should invest in something like reading and testing something like Thinking in Java, or just practice more and more Android Development.

[APP] WearShell

Having a LG G Watch for a while I thought that it would be interesting to run code directly on the watch without having to create an APK. Sometimes I just wanted to run some code snippets on the watch and view the result instantly.
Creating a complete project, compiling and deploying the APK on the Wear device is quite time consuming and somewhat annoying.
I tried to write an app to execute BeanShell code directly on the Wear device. This is all experimental and the possibilities are quite limited compared to an regular app, but for an execution of some code snippets that seemed to be a good idea.
The result is Wear Shell, an app that consists of a mobile and a Wear part. The mobile part moves the code for execution to the smart watch, collects the result and passes it to the calling application.
So I hope owners of an Android Wear smart watch have fun with the app and find it as interesting as I did to explore things from the perspective of a watch.
The complete blog post can be found here: Wear Shell - Exploring Android Wear
Now also available on Google Play.
Current Version
0.5.0
Download
WearShell APK
Extensions
Additional BeanShell Commands
Screenshot
{
"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"
}
Does this run java code only?
I had an idea of displaying web view info...like some nfl scores and stats think that be pretty sweet
After reading I think I found my answers, still pretty cool
Thank you so much. You don't understand what a pain in the ass it is to have to get on my laptop every time I want to execute a simple command in the watch.
I just realized how great this project was, yet so long time it has raised not much attention... The barrier for most readers may be the complicated JAVA source codes, where a lot of people may choose easier Python when using sl4a.
well, I just started as a newbie. My little suggestion is to add some notification push examples (main function of watch isn't it?) to attract more people.
For example I wrote a toast
import android.widget.Toast;
Toast.makeText(context, "message", Toast.LENGTH_SHORT).show();
I am also wondering if it is possible to popup or send a image to watch..
I need some time to understand the intent. But honestly I will appreciate if anyone can tell me how to call it through "am" or "tasker intent".
Besides, is there an option to hide the running popup?
After half day of trying, I found it hard to go on. The main reason is there lacks a tutorial explaining what commands and libraries are available and what are not.
For example, the desktop version I can use classBrowser() but no longer available in wear (apparent for a window, but what about others..).
For example, I can import android.widget.Toast but cannot import android.support.v4.app.NotificationCompat.WearableExtender; Besides, the error output is no so user-friendly that error only shows when later calling.
As a beginner should not use such an ineffective way that I try every command/library to see if there is an error.
Any resources for helping?
Androd Wear supports almost the complete Android API.
Here are the exceptions:
android.webkit
android.print
android.app.backup
android.appwidget
android.hardware.usb
The Wear app does not include any support library, so android.support.v4 classes are not available.
Nevertheless you should be able to use notifications the same way you do on a normal Android device.
Here is an example:
Code:
import android.app.Notification;
import android.content.Context;
noti = new Notification.Builder(context)
.setContentTitle("Title")
.setContentText("Text")
.setSmallIcon(com.android.internal.R.drawable.emo_im_cool)
.build();
​
notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(3, noti);​
I can't get exec intent to work. I tried Tasker, am and custom app and none seem to work.
Code:
Intent intent = new Intent("de.fun2code.android.wear.shell.EXEC");
intent.putExtra("bsh", "source(\"/sdcard/alwaysoff.bsh\");");
sendBroadcast(intent);
(File is there, if I execute same exact code via web interface it works.)
Any ideas?
I've noticed that WearShell only works when my phone's screen is on and unlocked. Thanks to qingtest and matejdro I have Tasker toggle theater mode in certain conditions, but it doesn't work if my phone's screen is off or it's locked. Secure Settings can allow Tasker to turn on the screen, but I haven't found anything to swipe at the lock screen to unlock it. That being the case, it'd be nice if WearShell could send the command while the phone is locked.
@joschi70 I followed the instructions in this topic http://forum.xda-developers.com/showthread.php?t=3098425 and I am using Tasker to send an intent. However, I noticed that sometimes the command is not sent to the watch if the phone is off and when I open the phone I find a message "Communicating with Wear Device".
Posted via Tapatalk
The Result Intent requires the phone to be unlocked.
I'm currently working on a new version that supports Broadcasts which should hopefully solve this issue.
The new version will support background service, an option to start the service on boot and an enhanced web interface.
Hope I can finish the new version in a couple of weeks.
WearShell 0.4 is available for download.
joschi70 said:
WearShell 0.4 is available for download.
Click to expand...
Click to collapse
Where can I find the change log. Is the intent result still needs the phone to be unlocked.
Posted via Tapatalk
The new version supports broadcasts, so the phone does not need to be unlocked.
The below info is also available inside the web interface.
Sending a Broadcast
Request
Action: de.fun2code.android.wear.shell.EXEC
Request String Extra: bsh
RequestCode Integer Extra: requestCode (optional)
Response
Intent Filter: de.fun2code.android.wear.shell.EXEC_RESULT
RequestCode Integer Extra: requestCode
Response String Extra: result
Hope this is working as expected.
joschi70 said:
The new version supports broadcasts, so the phone does not need to be unlocked.
The below info is also available inside the web interface.
Sending a Broadcast
Request
Action: de.fun2code.android.wear.shell.EXEC
Request String Extra: bsh
RequestCode Integer Extra: requestCode (optional)
Response
Intent Filter: de.fun2code.android.wear.shell.EXEC_RESULT
RequestCode Integer Extra: requestCode
Response String Extra: result
Hope this is working as expected.
Click to expand...
Click to collapse
Thanks a lot. It is working fine and serve my purpose.
joschi70 said:
The new version supports broadcasts, so the phone does not need to be unlocked.
The below info is also available inside the web interface.
Sending a Broadcast
Request
Action: de.fun2code.android.wear.shell.EXEC
Request String Extra: bsh
RequestCode Integer Extra: requestCode (optional)
Response
Intent Filter: de.fun2code.android.wear.shell.EXEC_RESULT
RequestCode Integer Extra: requestCode
Response String Extra: result
Hope this is working as expected.
Click to expand...
Click to collapse
I can't seem to receive the result intent inside of Tasker. I have tasker sending a piece of inline beanshell to the watch, but I can't seem to get any response. That said, my beanshell script doesn't return anything, could that be the reason? Or should I still be receiving something as a result? I have attempted to clone the %result variable that the userguide says should be created to %RESULT (global) but it's empty when I check.
EDIT: My apologies, I answered my own question and got the result to appear in a test task.
By the way, great app! You solved my problem with not being able to automate theater mode.
hello, is possibile send file smartphone to smartwatch?
or play sound file of smartphone in to smartwatch?
thanks
Inviato dal mio SM-N9005 utilizzando Tapatalk
Cool! I will try this sometime.
How Do You Send A Browser Intent To Wearshell From Tasker?
First off this app has so much potential and it's so cool. I admit I don't have much skill with Java or scripting, and I've looked all over the Internet for a tutorial on how to do this but I can't find one. All I want to know is how to send a browser intent to wear shell from Tasker. I put UC mini browser on my Huawei watch and it is working, and I can run Google searches from a tasker APK that I put on the watch, but that's a little slow and consumes a lot of battery. If I knew how to send an intent from Tasker to wearshell I think that would be faster and save battery. I have AutoVoice set up perfectly to intercept Google Now commands on my Galaxy Note 3, but the ability to backfeed commands to wearshell would be so awesome. I also think it is so cool that this app will allow commands to be sent to my watch without debugging being enabled.
The BeanShell code for opening an URL should look like this:
Code:
import android.content.Intent;
import android.net.Uri;
uri = "http://xda-developers.com";
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
joschi70 said:
The BeanShell code for opening an URL should look like this:
Code:
import android.content.Intent;
import android.net.Uri;
uri = "http://xda-developers.com";
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
Click to expand...
Click to collapse
I appreciate the help. I input this into the "data" section of tasker's 'send intent' action, as well as the 'extra' section. it did open the wearshell app on my phone showing the server is running though. thanks for helping someone with no coding knowledge. I'll keep trying variations of this.
EDIT: got it working by just putting a "bsh:" in the beginning of that code in the 'Extra' section.. this is awesome and so fast and uc mini so fast over bluetooth .. wow my projects hardly ever exceed my expectations, thanks Wearshell !

[CLOSED][APP][XPOSED][6.0+] Use Xposed without developing a module

{
"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"
}
XPrivacyLua custom hook definitions
By using XPrivacyLua you can define Xposed hooks and apply them to any app at run time (so, rebooting your device is not necessary). You can write hook code on your device in Lua, which is quite easy to learn.
See the documentation about how to define hooks.
Although XPrivacyLua has 'privacy' in its name, new hooks don't need to be privacy related at all. Disabling the built in privacy related hooks is a matter of selecting another collection of hooks.
This XDA thread is meant to discuss defining hooks, with the restriction that hook definitions must serve a legally allowed purpose. This XDA thread is not meant to make you a developer, so at least some development experience is expected, which means that you'll need to be able to figure out where to hook yourself and that you'll need to be able to write Lua scripts yourself.
XDA:DevDB Information
XPrivacyLua hook definitions, Xposed for all devices (see above for details)
Contributors
M66B
Xposed Package Name:
Version Information
Status: Beta
Created 2018-01-28
Last Updated 2018-04-01
Could there be a generic "always return true" lua script?
And when building a definition, what does it mean to be in a group and collection? Do I just put anything there or do I have to call them something particular?
Well, I'm trying but I'm lost. Just trying to setAnalyticsCollectionEnabled
https://firebase.google.com/support/guides/disable-analytics
Code:
public void setAnalyticsCollectionEnabled (boolean enabled) = false
supposedly disables Firebase Analytics (which apparently 67% of the top 200 apps use).
My definition looks like
Collection: privacy
Group: firebase
Name: firebase.analytics
author: whatever
class: com.google.firebase.analytics
method:setAnalyticsCollectionEnabled
parameter type: void
return type: boolean
min/max sdk: 1/999
lua script: @generic_false_value I suppose I can use this?
Even if this looks valid, it feels like maybe this wouldn't fire unless certain other things happen first? Looking at your hooks.json for google analytics it looks like you had to maybe set a chain of events to occur to get to the point of controlling the method you intend to make changes?
jawz101 said:
Could there be a generic "always return true" lua script?
And when building a definition, what does it mean to be in a group and collection? Do I just put anything there or do I have to call them something particular?
Well, I'm trying but I'm lost. Just trying to setAnalyticsCollectionEnabled
https://firebase.google.com/support/guides/disable-analytics
Code:
public void setAnalyticsCollectionEnabled (boolean enabled) = false
supposedly disables Firebase Analytics (which apparently 67% of the top 200 apps use).
My definition looks like
Collection: privacy
Group: firebase
Name: firebase.analytics
author: whatever
class: com.google.firebase.analytics
method:setAnalyticsCollectionEnabled
parameter type: void
return type: boolean
min/max sdk: 1/999
lua script: @generic_false_value I suppose I can use this?
Even if this looks valid, it feels like maybe this wouldn't fire unless certain other things happen first? Looking at your hooks.json for google analytics it looks like you had to maybe set a chain of events to occur to get to the point of controlling the method you intend to make changes?
Click to expand...
Click to collapse
The built-in scripts are not meant for general use because they might change over time breaking stuff that depends on them. Therefore imported definitions are not linked against the built-in scripts. If needed, you can simply copy and paste the Lua script from another (built in) definition. Copying guarantees your definition will keep working, even when the built-in scripts are changed or even removed.
Calling setAnalyticsCollectionEnabled requires access to an instance of FirebaseAnalytics, which apps needs to get by calling getInstance. So, hook getInstance to call setAnalyticsCollectionEnabled(false) and hook setAnalyticsCollectionEnabled to prevent an app from turning analytics on again.
Restricting Google Analytics (available in the next release of XPrivacyLua) works similar:
https://github.com/M66B/XPrivacyLua/blob/master/app/src/main/assets/ga_getinstance.lua
https://github.com/M66B/XPrivacyLua/blob/master/app/src/main/assets/ga_setdryrun.lua
You can also wait until I have added this ...
But firebase isn't necessarily the same thing, right?
jawz101 said:
But firebase isn't necessarily the same thing, right?
Click to expand...
Click to collapse
No, Google Analytics and Firebase Analytics are not the same and need different definitions.
Restricting Firebase Analytics works properly with these hook definitions:
https://github.com/M66B/XPrivacyLua/commit/1708fc6e4a15cef85cb973f5c08286d90d3ca806
jawz101 said:
And when building a definition, what does it mean to be in a group and collection? Do I just put anything there or do I have to call them something particular?
Click to expand...
Click to collapse
With the latest version of XPrivacyLua / companion app you can change the collection of hooks to use in XPrivacyLua. The default is to use the collection 'Privacy'. You can define your own collection by definition hooks with a new collection name. There can only be one collection active at one time, so if you want to add your own definitions to the built-in privacy collection you'll have to use the collection 'Privacy'. Basically collections exists to allow using XPrivacyLua for things other than privacy.
Groups are listed in the XPrivacyLua app and make it easy to apply a group of hooks to one or more apps. XPrivacyLua cannot and will not handle applying individual hooks to keep things simple, but I might add this to the pro companion app in the near feature. For now you can rename a group of an existing hook definition to be able to apply it separately in XPrivacyLua.
Edit: this has been clarified in the documentation too now: https://github.com/M66B/XPrivacyLua/blob/master/DEFINE.md
I still have some questions on when,where,how etc.... but I will wait until I can dedicate more time to playing with this.
I do have a feature request.
could there be a sort of drop down box that queries all valid entries for each item when creating a custom definition.
for example...
when creating a custom definition, when taping on the line for group, you would just type a new group (as it is now) but if there was a drop down arrow at the end of the line that could give a list of currently used groups and then the user could just click the listed group instead of typing and it would auto-fill that field.
maybe even more useful would be for the other items like Name,Class, Method etc...
where it could show possible entries. That would help a lot.
... I turned on notifications for your new Firebase rules. I would think a bunch of apps I have use Firebase Analytics. @M66B Have you seen any apps trigger it yet?
Even if the app imported Firebase Analytics library and gathers Firebase Analytics but never uses the setAnalyticsCollectionEnabled() method in its own code would it mean this hook will never trigger?
With the latest version of XPrivacyLua / companion app you can change the collection of hooks to use in XPrivacyLua. The default is to use the collection 'Privacy'. You can define your own collection by definition hooks with a new collection name. There can only be one collection active at one time, so if you want to add your own definitions to the built-in privacy collection you'll have to use the collection 'Privacy'. Basically collections exists to allow using XPrivacyLua for things other than privacy.
Click to expand...
Click to collapse
Thanks:highfive:.
This is just a suggestion but if this was my app I would break these 2 elements out to separate screens from the definition builder. You would define collections and groups in a separate spot, and then when building rules the collections and groups would pull in as a selectable dropdown. Avoids typos and helps to explain how there can be only one active collection for XPrivacyLua.
mnjm9b said:
I still have some questions on when,where,how etc.... but I will wait until I can dedicate more time to playing with this.
I do have a feature request.
could there be a sort of drop down box that queries all valid entries for each item when creating a custom definition.
for example...
when creating a custom definition, when taping on the line for group, you would just type a new group (as it is now) but if there was a drop down arrow at the end of the line that could give a list of currently used groups and then the user could just click the listed group instead of typing and it would auto-fill that field.
maybe even more useful would be for the other items like Name,Class, Method etc...
where it could show possible entries. That would help a lot.
Click to expand...
Click to collapse
I will see what I can do for collection and group, but all the other fields are flexible and depend on the hook.
jawz101 said:
... I turned on notifications for your new Firebase rules. I would think a bunch of apps I have use Firebase Analytics. @M66B Have you seen any apps trigger it yet?
Even if the app imported Firebase Analytics library and gathers Firebase Analytics but never uses the setAnalyticsCollectionEnabled() method in its own code would it mean this hook will never trigger?
Click to expand...
Click to collapse
An app will normally not disable/enable analytics given the default is enabled and the user has mostly no choice in this. So see this hook as a safeguard to prevent an app enabling analytics again after we disabled it in another hook
M66B said:
An app will normally not disable/enable analytics given the default is enabled and the user has mostly no choice in this. So see this hook as a safeguard to prevent an app enabling analytics again after we disabled it in another hook
Click to expand...
Click to collapse
Would there be a way to introduce the app to calling it? Or maybe that's what you're implying. Also, have you noticed that system and google apps seem to gray out the read identifiers permission? Ex: set read identifiers as restricted on Android Webview or Google Photos/Maps/Google TTS. Turns pink Get out of XPrivacyLua and open it again. Read Identifiers is gray. (I'm on LineageOS if that matters)
jawz101 said:
Would there be a way to introduce the app to calling it? Or maybe that's what you're implying. Also, have you noticed that system and google apps seem to gray out the read identifiers permission? Ex: set read identifiers as restricted on Android Webview or Google Photos/Maps/Google TTS. Turns pink Get out of XPrivacyLua and open it again. Read Identifiers is gray. (I'm on LineageOS if that matters)
Click to expand...
Click to collapse
Normally an apps doesn't call the function. Maybe if the user can choose to opt in or opt out, but this is rarely the case.
The other thing should go into the XPrivacyLua XDA thread, but I will look into it anyway.
M66B said:
I will see what I can do for collection and group, but all the other fields are flexible and depend on the hook.
Click to expand...
Click to collapse
Thanks, That's a good start.
Maybe if the "PRO" app takes off enough for you to bother you could charge extra for the expanded feature of having the drop lists change depending on the choices made?
I did have a moment to look over a definition I was playing with for "TIME"
it serves no real purpose so I gave up early but if I could get a better understanding on why it doesn't work it could help with actual ones.
using the FINGERPRINT example I made several other entries that all worked fine but this one caused issue.
I assumed it was because according to https://developer.android.com/reference/android/os/Build.html the type for TIME wasn't "String" but "Long"
this is the last one I tried...
Code:
{
"collection": "Privacy",
"group": "Read.Device",
"name": "Build.TIME",
"author": "M66B",
"className": "android.os.Build",
"methodName": "#TIME",
"parameterTypes": [],
"returnType": "long",
"minSdk": 1,
"maxSdk": 999,
"enabled": true,
"optional": false,
"usage": true,
"notify": false,
"luaScript": "function after(hook, param)\n param:setResult("unknown")\n return true\nend\n"
}
I was also playing with "SUPPORTED_ABIS" which also didn't work and the type was "Sting []" instead of just "String" so I was thinking that was the problem also.
@mnjm9b You are returning a string (series of characters) as a long (number). Try returning just a number (without the quotes).
String[] is an array (mulitple strings), so you need to return an array as well. But I don't know how to do that in Lua right now
Namnodorel said:
@mnjm9b You are returning a string (series of characters) as a long (number). Try returning just a number (without the quotes).
String[] is an array (mulitple strings), so you need to return an array as well. But I don't know how to do that in Lua right now
Click to expand...
Click to collapse
You are 100% right.
Returning a string array is not trivial. Look at 'generic_empty_string_array.lua' about how to do this.
Namnodorel said:
@mnjm9b You are returning a string (series of characters) as a long (number). Try returning just a number (without the quotes).
String[] is an array (mulitple strings), so you need to return an array as well. But I don't know how to do that in Lua right now
Click to expand...
Click to collapse
so in my example the returnType instead of "long" should be a number like 0 without quotes?
I tried that and it still doesn't work.
---------- Post added at 08:55 PM ---------- Previous post was at 08:54 PM ----------
M66B said:
You are 100% right.
Returning a string array is not trivial. Look at 'generic_empty_string_array.lua' about how to do this.
Click to expand...
Click to collapse
thanks for this, I guess I am in WAY over my head.
mnjm9b said:
so in my example the returnType instead of "long" should be a number like 0 without quotes?
I tried that and it still doesn't work.
Click to expand...
Click to collapse
No. the return type was correct. That specifies what type of object you are expected to return. What you need to change is what you then actually return, which is
Code:
param:setResult("unknown")
to
Code:
param:setResult(12345678)
@M66B
Thank you for your work, if i understand right, you provide us an programmable interface that will execute command lines written in Lua language without having to create a complete module in JAVA for XPosed?
From what i understood in your initial post, you indicate that we must install your module "XPrivacyLua", then that one disposes there after of the possibility to apply for the applications which one wishes, lines of codes written in Lua language and which do not necessarily have to relate to the logic of rights of access concerning privacy?
If yes then we must necessarily install XPrivacyLua even if in view of all your work provided on it the basic functions do not interest me forcibly?
All this seems to be promising however :good:
Rom said:
@M66B
Thank you for your work, if i understand right, you provide us an programmable interface that will execute command lines written in Lua language without having to create a complete module in JAVA for XPosed?
Click to expand...
Click to collapse
Yes.
Rom said:
From what i understood in your initial post, you indicate that we must install your module "XPrivacyLua", then that one disposes there after of the possibility to apply for the applications which one wishes, lines of codes written in Lua language and which do not necessarily have to relate to the logic of rights of access concerning privacy?
Click to expand...
Click to collapse
Yes.
Rom said:
If yes then we must necessarily install XPrivacyLua even if in view of all your work provided on it the basic functions do not interest me forcibly?
All this seems to be promising however :good:
Click to expand...
Click to collapse
You'll need XPrivacyLua to install and run defined Xposed hooks written in Lua, but you don't need to use the built in privacy related hooks.
The companion app allows you to switch to another collection of hooks you've written, in effect disabling the built-in privacy related hooks.
Try it and I will help you when needed and in the process I will update the documentation where needed.

How do I integrate HMS to my game using HMS Unity Plugin 2.0? — Part 1

{
"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​Hello everybody! In this article, I will be introducing the brand new version of HMS Unity Plugin version 2.0! Yes, it is out and it will make your life much easier, even when compared to the previous version of the plugin 1.2.0!
The HMS Unity Plugin is a tool that helps developers to quickly integrate Huawei Mobile Services (HMS) to their games in Unity without worrying about the boilerplate codes that has to be written in the background. All the necessary backend code is dealt with for you, and all you have to do is to focus on your own game and HMS features.
In this article, I will be using my own game as a scenario to quickly explain the steps required for you to integrate many HMS kits with a few clicks and/or lines of code. To be specific, I am using the version 2.0.1 for this article.
Before diving into details, you can check out here, the plugin’s GitHub page, if you think you are experienced enough with the plugin and that you do not require any specific scenario to start using the plugin. Readme already has general details about how to start using the kit.
Please note that I developed this game and used the plugin for this article series in Unity editor version 2019.4.18f1. For 2020 version of the Unity, you should be able to do the same steps with the same version of the plugin. For 2018 or other versions, please check out here, the releases page, for the corresponding plugin release (if any) and for the latest updates.
I further suggest that you download the latest version of the plugin for the corresponding Unity version, although I have used version 2.0.1 here. Details on how to use/import the plugin will follow, but I wanted to let you know beforehand.
About My Game​Let me quickly introduce my game to you, so that during the phases of integration, it makes sense to you why I am implementing the plugin features in this way.
It is a hypercasual game called Raining Apocalypse, where you simply escape from the rain! You are the cool fire character that run horizontally. The more rains you run away from the more points you score. So, as you can see, very simple and affordable to implement.
I developed this game using a Udemy course and the source code is not completely written by me. However, we will not focus on the game development parts anyway, we will integrate the HMS kits to our game to increase our chances of survival in the game industry.
It consists of two scenes: main menu scene and game scene. It has several scripts attached, some of which we will use in the integration.
I will integrate “Account Kit, Ads Kit, Push Kit, Game Service, IAP, Analytics Kit and Crash Kit” to my game. For this part 1 of the article, I will talk about Account Kit, Ads Kit, Analytics Kit, Crash Kit and Push Kit. Game Service and IAP will be talked about in Part 2 of the series.
It looks too many and seems to cost the developers a lot of time, but not with Plugin 2.0 and you will see how, if you read on.
Development Process​To start using the plugin you must go here, the readme of the official GitHub page of the plugin and complete the phases, starting from the phase called “1 — Register your app at Huawei Developer” to “4 — Connect your game with any HMS Kit”, so that the AppGallery Connect side of your application is done. HMS requires AppGallery Connect configurations to correctly work with the in-game features you want to implement.
I will, from now on, assume that you have completed the first 3 phases and now ready to implement the 4th phase and onwards. You can continue using the following phases for the kits as well; but here, I will merge them with a real life scenario, i.e. my game, so that you can better understand how those features would work in your own game. By this way, you can decide easily where to put those methods in your own game.
Now, assuming that you are done with the AGC side, let’s get to the coding. I will talk about AGC side a bit in some of the kits I explain as well.
Coding Phase​Let’s start with Account Kit and Ads Kit. The main menu scene of my game has a logo and a play button to start the game. What I want to add is a banner ad to the bottom and also to implement sign in functionality. By this way, I will show 320*50 (or any size you choose) ads to the users at the beginning of my game. Also, since I do not want to proceed to the game without the user signed in, I will implement the sign in functionality so that when I try to use the other kits in-game, I do not have to deal with sign in process again.
To start using any kit, you must import the plugin (downloaded from the releases page) and click on the kits that you want to use. Mine currently looks like this:
Clicking them will add a manager to your game screen. They are coming with DontDestroyOnLoad() function by default, so you do not have to worry about carrying it over to the other scenes. However, it is strongly suggested that you do this in the outermost scene, so this carry-over process is smooth and bug-free. I do it in my main menu scene because it comes first, and the game scene opens the second.
I have my own manager script called EnesGameManager.cs to control the behaviour of kits and game-specific functionalities.
Before every use of managers, you must call them with .Instance because the plugin uses the singleton pattern to implement the managers. That is also helpful in changing scenes all you like because the plugin will delete the unnecessary copies of the manager and will make sure that you only work with the one and the only instance. This will save you from coding overhead and wrong instance usage.
Account Kit​After ticking the box, HMSAccountManager is added to the scene. All you have to do is to add the below line to anywhere you choose as per your own game logic. You can place it inside a new method to add a button click to the play button, for example.
HMSAccountManager.Instance.SignIn();
Important Note: If you plan to use GameService, it has automatic sign-in functionality. Instead of using Account Kit, you can just enable the GameService, tick the box (“Initialize on Start”) under Game Service tab and your app will do auto sign-in every time the user opens the app. If this is not what you want, use of Account Kit is required and GameService function should be manually initialized. All of the details about this can be found in the part 2 of the article, which is here.
GameService is dependent on AccountKit anyway, so even if you do not use Account Kit to login (which is perfectly fine), GameService login system will use it for you in the background.
Ads Kit — Part 1​Ads Kit has three types of advertisements as of the publish date of this article. If you are reading this later than the publish date, some new types of ads might have been added to the plugin, so I would suggest you to check them out as well. Ads Kit, right now, supports “Banner Ads, Interstitial Ads and Rewarded Ads”. I will be using banner ads and interstitial ads in my game. Since the interstitial ads will be implemented in the game scenes, in this part 1, I will only show how to implement banner ads.
To enable the ads you want to use, just tick the corresponding boxes. That is very easy. Also, if you want to use test ads like me, check that box too. It will replace any ID you enter above with the test ID, so you can test the layout of ads in your game for example, before getting a real ID. If you have the ID already you can uncheck the test ID box, enter the ID and click save. Replacing does not mean you will lose the already-entered ID, but you will see the test ads from now on, until you uncheck the box.
The default size is 320*50 and the default position is POSITION_BOTTOM. If you require different sizes and positions, you can only change them inside of manager script in this version of the plugin. You can check Huawei -> Scripts -> Ads folder to reach the manager script and configure as per your needs.
If you build now, you should get your ads like below. You can work on alignment yourself to match the elements.
There is one more thing left. This banner ad will show in every screen you will be opening from now on. For my case, it will be present on my game screen if I press play button; which is not what I want. Thus, in the game scene, I will call below one line code to hide the ads because it is the behaviour I want. You can call this code piece in any Start() function of the active object scripts.
HMSAdsKitManager.Instance.HideBannerAd();
As you can see, no initialization etc. required. HMSAdsKitManager will remain on your other scenes and can be directly called by using its instance.
If you do not want the banner ads in your main screen and want it in other scenes, you can always use the above hide code to hide it in the beginning and call the below show method to show it anywhere you like.
HMSAdsKitManager.Instance.ShowBannerAd();
That’s it for banner ads. Very short, very simple.
Ads Kit — Part 2​I also want to use interstitial ads in my app. The scenario I want to use it is when the user dies, before showing a lose screen to retry, I want to show interstitial ads, unless the user has purchased the remove_ads product (which I will talk about in IAP section).
To implement this, I need to put the code into the proper place in my own game code. There is no one way to do it. If you have a similar scenario like me, you can also follow my code and find your corresponding code and implement your own interstitial ads logic.
In my player script, I have the TakeDamage function where I control the damage inflicted on my player. It also controls the death, when the health drops below zero. So here, when the player dies, I call interstitial ad show code to display the user interstitial ads. The if check can be ignored now and will be talked about in IAP section.
public void TakeDamage(int damageAmount)
{
source.Play();
health -= damageAmount;
if (health <= 0)
{
healthDisplay.text = "0";
HMSAnalyticsManager.Instance.SendEventWithBundle("$GameCompleted", "Score", score.ToString());
Destroy(gameObject);
if (!GameObject.Find("EnesGameManager").GetComponent<EnesGameManager>().isAdsRemoved)
HMSAdsKitManager.Instance.ShowInterstitialAd();
losePanel.SetActive(true);
HMSAchievementsManager.Instance.GetAchievementsList();
}
else
{
updateHealthDisplay();
}
}
Basically, just calling the ShowInterstitialAd() function is enough to show the ads. Once the player dies, it will be shown immediately and after the user closes it, the lose panel will be shown.
Like most kits, there are callbacks that you may want to implement. For example, interstitial ads has “OnInterstitialAdClosed” callback that can be implemented. If you want to control what will happen right after the user closes the interstitial ad, you can implement this by using the code below in start function.
void Start()
{
//...
HMSAdsKitManager.Instance.OnInterstitialAdClosed = OnInterstitialAdClosed;
}
The second “OnInterstitialAdClosed” is the name of the function that you will be defining. So it can be changed to whatever you like. You can generate a new function manually by using the name you defined in the right hand side of the equal sign. However, since some callbacks come with parameters from the plugin, it is recommended that you show the potential fixes and generate one from there automatically. By this way, you will also which parameters, if any, will be returned from the callback. You can check other methods in all kits by typing “HMS…Manager.Instance.On…” and see which callbacks are supported.
Analytics Kit​In the code above, you can see an AnalyticsManager instance is used. That is the whole implementation of analytics kit I have in my game. After I enabled it from the Kit Settings menu in the Unity Editor, I can call HMSAnalyticsManager however I like, as in the other managers. Here, my scenario for Analytics Kit is sending the score of the player to the server to see how much score people are achieving. You can use, just as I did, SendEventWithBundle function to send whatever items need to be sent as your game logic requires. The function requires an EventID, key and a value to be sent that can be of type string or int. That’s it and now you can check if the parameters are coming to AGC console by checking the tab “Real-time Overview”
Some of the events are predefined. As long as you enable Analytics Kit, they will be sent to the console anyway, even if you do not code anything in your game. If you cannot see your own custom event here, I would suggest adding that even manually from the Events tab close to bottom in AGC console. You can also look for support from the Huawei Developer website and/or forum.
Crash Kit​Crash Kit, when clicked, is automatically implemented thanks to the plugin. You should see crash reports in AGC Console, if any crash appears. You can also deliberately cause your app to crush, but how to do so is outside the scope of this article.
Push Kit​Push Kit, like Crash Kit, is also automatically enabled when you tick the box besides it. It is complete and ready to use. Simple as that, you should go to AGC Console, create a notification and you should receive notification depending on the time you set.
Tips & Tricks​
Do not forget to get the agconnect-services.json file from the AGC and paste it to the StreamingAssets folder. The folder must be placed inside Assets folder of the Unity files.
In case any method or code piece that I shared will not work and you face any compiler complaints, make sure that you have imported the right libraries with “using” keyword. For any usage of the plugin, first line below is required and the other two lines are needed for most functions related to the kits. Make sure you imported them to use them smoothly.
using HmsPlugin;
using HuaweiMobileServices.Game;
using HuaweiMobileServices.Utils;
It is very normal that your game is different and the scenario you wanted this kits may differ from mine. That’s why, I always talked about how my need/scenario for the kit and then implemented it. If you are having trouble how to convert this to your own game logic, try to understand what I did and where, so you can implement the similar functionality where you want it to be in your own game.
Please make sure that your package name ends with either . Huawei or with .HUAWEI if you want to use IAP in your game. If you used another package name, please change it for AppGallery. Otherwise, IAP will not work. IAP will be talked about in part 3 but I wanted to warn here, so if you do not have an existing game yet, you can start off right.
Conclusion​In this article, we integrated many kits to our game. This was not just a “to integrate, do this” kind of article, but rather I tried to show you a real game scenario, so while you are applying this article to your game, you will hopefully have a better understanding. With Plugin 2.0, the speed of integration has increased dramatically, reduced down from days to perhaps hours depending on the complexity of your app.
I hope that this article has been helpful for you. You can always ask questions below, if you have anything unanswered in your mind.
Remaining two kits will be talked about here, in the part 2.
See you there!
References​
HMS Unity Plugin 2.0 Branch (Github Page)
Documentation of every single kit in Huawei Docs (Links are present in the GitHub readme)
Checkout in forum

How do I integrate HMS to my game using HMS Unity Plugin 2.0? — Part 2

{
"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​If you are not coming to this article from the Part 1 of the series, you can read here. This is the second part of our HMS Unity Plugin 2.0 integration guide. As you know, I wanted to talk about a part of GameService here because it requires a bit more work, not because of the plugin but because of its intrinsic nature. Adding products, managing behaviors, configuring achievements etc. take a bit more time in the AGC side. I will try to give as many details as I can give in this article; but since some of the topics are not directly related with the plugin, you may further research on how to do the tasks that I do not extensively talk about here.
I will be talking about just the Achievements parts of the GameService. However, it also has the capabilities of SaveGame and Leaderboard. You can read more about them in other articles and believe me, they are as easy to integrate as the ones I talk about, thanks to the HMS Unity Plugin 2.0.
This article also assumes that you have completed the steps in Part 1, at least the ones that are essential. GameService is already dependent on Account Kit you must check Account Kit as well from the Kit Settings menu, even if you will not use it directly in your game. (Plugin should automatically tick it for you once you tick GameService)
You do not have to integrate other kits to integrate these two kits, but some AGC side requirements are standard for all kits. I will talk about the specific parts that are about GameService here and IAP (In-app purchases) in part 3.
Without further ado, let’s get started.
GameService​After enabling GameService in HMS Settings (aka Kit Settings) menu, a “Game Service” tab will be automatically added to the settings menu, as can be seen below in the screenshots. Now, I walk you through GameService step by step for those who want a bit of additional information.
Sign-In Function Implementation​As I have warned in part 1, for the use of GameService, sign-in is required. This must be either done through Account Kit by yourself, or through GameService.
The easiest way to the do this is to just to check the box at the bottom of GameService tab. When you tick “Initialize On Start”, whenever users start your game, your game will try to log the user in immediately and they will see the “Welcome *username*” greeting message immediately if they logged in at least once in your game.
In the first-ever login in your game, they will be directed to the Huawei login page automatically, which will be done at the very first opening of your app. If you choose to do this, you do not even have to implement Account Kit. That’s it, login is done and you are ready to continue with just one click.
If you opt for not checking the box because this is not a desirable in-app behavior for you, then you must initialize the GameService manually and use the Account Kit in your own logic to log the user in.
It requires a bit of code but is not hard at all. Let’s assume that you sign-in at the Start() function of your app using Account Kit. What you have to do is to implement the SignInSuccess callback. If login is successful, success callback will be automatically executed and in there, you must initialize the GameService with just one line of code.
void Start()
{
HMSAccountManager.Instance.SignIn(); //sign the user in HMSAccountManager.Instance.OnSignInSuccess = OnSignInSuccess;
//implement callback on Start()
}
private void OnSignInSuccess(AuthAccount obj)
{
HMSGameManager.Instance.Init();
}
That’s it for the manual control. Now, you control where you want to sign your users in and also initialize the GameManager so that you can use Achievements, Leaderboards and SaveGame features.
I suggest that whichever way you choose, you do this at the first scene of the app (like a main menu etc.) and not inside the game itself, so users will not be bothered by sign-in process in-game.
Achievements​I want to add achievements to my app so when the user has done certain actions, I will reward them by unlocking some achievements. There are mainly two actions required to be done by you, the developer: First, add achievements to your app in AGC and get their ID. And second, enter the IDs to Achievements part of the plugin and implement in-game logic. That means, you need to determine where you will grant your users an achievement in your game. What kind of actions are needed to be carried out to get them?
In my case, this process is very simple. I have “Beginner, Medium and Master Scorer” achievements defined and I grant them whenever the user completes a certain score in my game. Since my game is very simple, the score is the utmost indicator of a “skilled” player, so I thought, why not?
First, let’s go to AGC (AppGallery Connect) together to add some achievements. You can go to AGC by using this link. Sign in to your developer account, click “My apps” and choose your game from the list. You will be directed to “Distribute” tab. From the left-upper bar, choose “Operate” tab instead. There, you will have “Product Management” tab opened at first from the left navigation menu, which I will use it for IAP later. Now, move to the Achievements tab to add some achievements to your game. Click Create on right to create an achievement.
You enter a name and a description to remember what this achievement is for. You can leave “incremental achievement” unchecked because I do not need it for this simple game. Also for the “revealed, hidden” option, what I did was to make the BeginnerScorer achievement revealed and the other two are hidden. So user will see them in achievements list but will not know what they are before achieving the previous achievement. You can configure them however you like. Make sure they are fitting to your game content, so users will try to play longer to achieve them. Also, I set the same logo for every one of them but I suggest you design different icons for each and every one of your achievements.
After you are done, it should look like something like this:
Do not release your achievements so you can test them. If you release them, they will be checked by AGC and be approved if they are proper. However, then, you cannot reset their progress even if you did not publish your game yet. Thus, to make sure that the development side works correctly, I will leave them as it is. Whenever you achieve them in your own game testing, you can just reset the progress and keep testing if you want to change something you do not like.
Now that I am done creating them, you can click “Obtain Resources” above and copy their IDs one by one. Then, paste them to our HMS Settings menu. After you copied them all, click “Create Constant Classes”, so HMS Unity Plugin can create a constant class for you.
The constant class will be called HMSAchievementConstants. Now let’s see how can I use them. I will need the “state”s of these achievements for my game implementation because I will check the states to grant the achievements one by one. Imagine a scenario where BeginnerScorer needs 15 points and MediumScorer needs 25 points to unlock. If the user surpasses 25 points in the first game, then the game would grant them consecutively in one run. This is not what I want, so I will access the achievement states and that requires Achievement objects. You do not have to use Achievement objects, you can just use the constant class to retrieve the IDs and immediately reveal and/or unlock them.
public void TakeDamage(int damageAmount)
{
//...
if (health <= 0)
{
//...
//Player is dead
losePanel.SetActive(true);
HMSAchievementsManager.Instance.GetAchievementsList();
}
}
Remember my TakeDamage function shown above. Since I will be unlocking achievements when the game is done, I will call my GetAchievementsList() function after the player dies. This function is necessary because it has several callbacks that which I will use. You should decide to call this function depending on your game logic and code structure. As I always do, I tell my structure in detail so you can project where you should put yours.
void Start()
{
//... HMSAchievementsManager.Instance.OnGetAchievementsListSuccess = OnGetAchievemenListSuccess;
HMSAchievementsManager.Instance.OnGetAchievementsListFailure = OnGetAchievementsListFailure; //optional
}
In the Start() function of wherever you will call GetAchievementsList() function, do as above. Basically, you are registering the these callbacks so when getting the achievements list is successful, the OnGetAchievemenListSuccess that you will write will be triggered. Failure callback is optional, you can track the errors and add some user warning if you like.
using System.Linq;
private void OnGetAchievemenListSuccess(IList<Achievement> achievementList)
{
//Implement your own achievement system here...
//Achievement beginnerScorer = achievementList[3]; -> Same thing as the line below
Achievement beginnerScorer = achievementList.First(ach => ach.Id == HMSAchievementConstants.BeginnerScorer); //Score of 15 is needed
Achievement mediumScorer = achievementList[4]; //Score of 25 is needed
Achievement masterScorer = achievementList[5]; //Score of 50 is needed
if (score >= 15 && beginnerScorer.State != 3)
{
HMSAchievementsManager.Instance.UnlockAchievement(beginnerScorer.Id);
//HMSAchievementsManager.Instance.UnlockAchievement(HMSAchievementConstants.BeginnerScorer); -> same as above
HMSAchievementsManager.Instance.RevealAchievement(mediumScorer.Id);
}
else if (score >= 25 && beginnerScorer.State == 3 && mediumScorer.State != 3)
{
HMSAchievementsManager.Instance.UnlockAchievement(mediumScorer.Id);
HMSAchievementsManager.Instance.RevealAchievement(masterScorer.Id);
}
else if (score >= 50 && mediumScorer.State == 3 && masterScorer.State != 3)
{
HMSAchievementsManager.Instance.UnlockAchievement(masterScorer.Id);
}
}
private void OnGetAchievementsListFailure(HMSException obj)
{
Debug.Log("OnGetAchievementsListFailure with code: " + obj.ErrorCode);
}
Let me explain the code above. It may look a bit complicated but it is not hard to understand. Since I registered to my callbacks, I need to implement them now. You need to implement the this callback yourself, so users can unlock achievements.
As I said, since I need the states, I use the objects of Achievement class. Normally, if I were not to care about the states, I would not even need them. I would just do:
HMSAchievementsManager.Instance.UnlockAchievement(HMSAchievementConstants.BeginnerScorer);
So, if you do not need states or other properties of Achievement class, you can also do the same. Your development cost is much less this way, thanks to the plugin. As you see, you do not even need to copy the long IDs to wherever you want to use them, you can just call constants class and use the IDs by the name you gave to them.
In the following part of the code, I get my achievements one by one from the callback parameter. A list already returned to me and I can pick what I want. Since I previously added 3 more achievements that I did not show you, my ordinal numbers start from 4. (you can check AGC console screenshot above)
Achievement beginnerScorer = achievementList.First(ach => ach.Id == HMSAchievementConstants.BeginnerScorer); //15 score is needed
Achievement mediumScorer = achievementList[4]; //25 score is needed
What I do is to get to the (4–1)rd index to get my beginner achievement. You can always match the indices of the achievements from the AGC console ordinals. There is also another way. If you import System.Linq, you can also use First function to get the achievements without using index numbers. Example is shown above. This is just to provide some alternatives for you.
In the rest of the code, I check the states and if they are not unlocked yet, or surely unlocked in the next step, I unlock my achievements. Since I made the other two achievements hidden, I also reveal them when the user unlocks the previous achievement. It is all under my control, so you can code your own logic however you like.
Also notice that I use the instance of HMSAchievementsManager when revealing and unlocking achievements. No further code required to call this because plugin handles the other cumbersome processes for you.
Achievements are done. You can see how I have become the master of my own game.
One little thing is left though. Users should be able to see what kind of achievements are there even if they are hidden. (It will be shown as hidden)
AppGallery already provides an interface for this, thus, if you want to implement this functionality you can just call one line function.
public void ShowAchievements()
{
HMSAchievementsManager.Instance.ShowAchievements();
}
Since I use a button click to call this function, I put the code in another local function. Depending on your requirements, you can call it directly.
Tips & Tricks​
There are certain other callbacks related to the kits that you use through plugin. I did not talk about them because they were irrelevant for my use case. You can always check them with IntelliSense suggesting while coding. It should suggest available callbacks after Instance.
Conclusion​I have integrated simple achievements to my game so that users could spend more time in my game. You can adjust the details I provided for your use case and devise a scenario that works for you.
I hope that this article has been helpful for you. You can always ask questions below, if you have anything unanswered in your mind.
The only remaining kit is IAP and it will talked about here, the part 3.
See you there!
References​
HMS Unity Plugin 2.0 Branch (Github Page)
Documentation of every single kit in Huawei Docs (Links are present in the GitHub readme)
Checkout in forum

Categories

Resources