When users unlock their phones, they will often see a red oval or circle in the upper right corner of some app icons. This red object is called an app icon badge and the number inside it is called a badge count. App icon badges intuitively tell users how many unread messages there are in an app, giving users a sense of urgency and encouraging them to tap the app icon to read the messages. When used properly, icon badges can help improve the tap-through rate for in-app messages, thereby improving the app's user stickiness.
{
"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"
}
HMS Core Push Kit provides an API for configuring app icon badges and allows developers to encapsulate the badge parameter in pushed messages.
It is a well-known fact that many users find such messages annoying, and a feeling like this can damage how users evaluate an app and make it impossible for the push message to play its role in boosting user engagement. This makes app icon badges a necessary complement to push messages, because unlike the latter, the former appears silently and thus won't bother users to check in-app events when it's inconvenient for them to do so.
So, how do we go about implementing app icon badges for an app? The detailed procedure is as follows.
Setting an App Icon Badge Using the Client APISupported Platforms
OS version: EMUI 4.1 or later
Huawei Home version: 6.3.29
Supported device: Huawei devices
Badge Development1. Declare required permissions.
Code:
< uses - permission android: name = "android.permission.INTERNET" / >
<
uses - permission android: name = "com.huawei.android.launcher.permission.CHANGE_BADGE " / >
"com.huawei.android.launcher.permission.CHANGE_BADGE " / >
2. Pass data to the Huawei Home app to display a badge for the specified app.
Code:
Bundle extra = new Bundle();
extra.putString("package", "xxxxxx");
extra.putString("class", "yyyyyyy");
extra.putInt("badgenumber", i);
context.getContentResolver().call(Uri.parse("content://com.huawei.android.launcher.settings/badge/"), "change_badge", null, extra);
Key Parameters
package: app package name.
class: entry activity class of the app that needs to display a badge.
badgenumber: number displayed in the badge.
Code:
boolean mIsSupportedBade = true;
if (mIsSupportedBade) {
setBadgeNum(num);
}
/** Set the badge number. */
public void setBadgeNum(int num) {
try {
Bundle bunlde = new Bundle();
// com.test.badge is the app package name.
bunlde.putString("package", "com.test.badge");
// com.test. badge.MainActivity is the main activity of an app.
bunlde.putString("class", "com.test. badge.MainActivity");
bunlde.putInt("badgenumber", num);
this.getContentResolver().call(Uri.parse("content://com.huawei.android.launcher.settings/badge/"), "change_badge", null, bunlde);
} catch (Exception e) {
mIsSupportedBade = false;
}
}
Special Situations1. Whether to continue displaying a badge when the app is opened and closed depends on the passed value of badgenumber. (The badge is not displayed if the badgenumber value is 0 and displayed if the badgenumber value is greater than 0.)
2. If the app package or class changes, the developer needs to pass the new app package or class.
3. Before calling the badge API, the developer does not need to check whether Huawei Home supports the badge function. If Huawei Home does not support the badge function, the API will throw an exception. The developer can add the try … catch(Exception e) statement to the place where the API is called to prevent app crashes.
Setting an App Icon Badge Using the Push SDKIn the downlink messaging API of Push Kit, three parameters in BadgeNotification are used to set whether to display the badge and the number displayed in the badge.
ParameterMandatoryTypeDescriptionadd_numYesintegerAccumulative badge number, which is an integer ranging from 1 to 99.
For example, an app currently has N unread messages. If this parameter is set to 3, the number displayed in the app badge increases by 3 each time a message that contains this parameter is received, that is, the number equals N+3.classYesstringClass name in App package name+App entry activity format.
Example: com.example.hmstest.MainActivityset_numYesintegerBadge number, which is an integer ranging from 0 to 99.
For example, if this parameter is set to 10, the number displayed in the app badge is 10 no matter how many messages are received.
If both set_num and add_num are set, the value of set_num will be used.
Pay attention to the following when setting these parameters:
1. The value of class must be in the format App package name+App entry activity. Otherwise, the badge cannot be displayed.
2. The add_num parameter requires that the EMUI version be 8.0.0 or later and the push service version be 8.0.0 or later.
3. The set_num parameter requires that the EMUI version be 10.0.0 or later and the push service version be 10.1.0 or later.
4. By default, the badge number will not be cleared when a user starts the app or taps and clears a notification message. To enable an app to clear the badge number, the app developer needs to perform development based on the relevant badge development guide.
5. The class parameter is mandatory, and the add_num and set_num parameters are optional.
If both of add_num and set_num are left empty, the badge number is incremented by 1 by default.
ConclusionApp icon badges have become an integral part for mobile apps in different industries. Those little dots can serve as a quick reminder which urges users to check what is happening within an app, in a way that is imperceptible to users. In this sense, app icon badges can be used to boost app engagement, which can well explain why they are widely adopted by mobile app developers.
As proven by this post, the API from Push Kit is an effective way for app icon badge implementation. The API enables developers to equip push notifications with app icon badges whose parameters are customizable, for example, whether the badge is displayed for an app and the number inside a badge.
The whole implementation process is straightforward and has just a few requirements on hardware and software, as well as several parameter setting matters that need attention. Using the API, developers can easily implement the app icon badge feature for their apps.
Related
Note : I'm just sharing the work of the XDA Member klinkdawg24.I haven't tested this method but I request the people to here to try implementing this in your apps and see.Here's the guide :
klinkdawg24 said:
This is a project that I whipped together to show developers how to implement a floating window type popup for their apps. An example usage would be quick reply to a sms message, email, or any other times quick reply would come in handy. It isn't limited to just that though, using this method, you will be able to completely recreate any activity in windowed form with very little code edits.
{
"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"
}
My brother an I have used this to create a quick reply for our app, Sliding Messaging Pro. The idea is basically the exact same as Halo, with almost the exact same implementation. We do it by extending the MainActivity in a pop up class, then using an overrode setUpWindow() function to set up your MainActivity in the window.
The full source is availible on my GitHub, found here: Floating Window GitHub
Play Store Link: Floating Window Demo
So now to the actual steps to creating your own "floating window popup" out of your apps MainActivity:
1.) First, we should add the styles that we are going to use to the styles.xml sheet.
These are the styles for the animation, of course you can define your own animation if you choose, these will bring the window up from the bottom of the screen and the close it to the bottom of the screen.
Code:
@anim/activity_slide_up
@anim/activity_slide_down
Now, this style is for the actual popup dialog box. You can play with the different values here all you want. We end up overriding some of these when we set up the window anyways, such as the dimming.
Code:
false
stateUnchanged
@null
true
true
@null
@style/PopupAnimation
true
false
2.) Now that your styles are set up, lets go ahead and add the new Popup activity to the manifest. You can see that we used the Theme.FloatingWindow.Popup style that we just defined in the last step. You will also have to add
Code:
xmlns:tools="http://schemas.android.com/tools"
to the xmlns declarations at the top of the manifest.
Code:
3.) One more thing that we have to put in before you have resolved all the errors here, the animations. Just copy and paste these two animations in separate files under the res/anim folder. Name one activity_slide_down.xml and the other activity_slide_up.xml
activity_slide_down.xml
Code:
activity_slide_up.xml
Code:
4.) Now that everything should be set up, we will make the actual popup activity! You can view my full code for this from the GitHub link, but basically, we are going to make a PopupMainActivity.java class and extend the MainActivity class. If you understand inheritance at all with java, you will know what this is doing. It is going to allow this PopupMainActivity class, when started, to override methods from the MainActivity to produce different outcomes.
The method that actually makes the windowed pop up I have named setUpWindow(). This means that whenever this activity is called instead of the main activity, it will use this method instead of the main activities setUpWindow() method. This is very convieniet since we don't want to do any extra work than we need to in this class. So here is the code for that class:
Code:
/**
* This method overrides the MainActivity method to set up the actual window for the popup.
* This is really the only method needed to turn the app into popup form. Any other methods would change the behavior of the UI.
* Call this method at the beginning of the main activity.
* You can't call setContentView(...) before calling the window service because it will throw an error every time.
*/
@Override
public void setUpWindow() {
// Creates the layout for the window and the look of it
requestWindowFeature(Window.FEATURE_ACTION_BAR);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND,
WindowManager.LayoutParams.FLAG_DIM_BEHIND);
// Params for the window.
// You can easily set the alpha and the dim behind the window from here
WindowManager.LayoutParams params = getWindow().getAttributes();
params.alpha = 1.0f; // lower than one makes it more transparent
params.dimAmount = 0f; // set it higher if you want to dim behind the window
getWindow().setAttributes(params);
// Gets the display size so that you can set the window to a percent of that
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
// You could also easily used an integer value from the shared preferences to set the percent
if (height > width) {
getWindow().setLayout((int) (width * .9), (int) (height * .7));
} else {
getWindow().setLayout((int) (width * .7), (int) (height * .8));
}
}
You can see what it does from the comments, but basically, it just initializes your main activity in a windowed for, exactly what we are trying to do!
5.) Now to actually have this method override something in the MainActivity, you must add the same method there. In my example, The method is just blank and has no implementation because i don't want it to do anything extra for the full app. So add this activity and the error that "your method doesn't override anything in the super class" will go away. Then you actually have to call this method from your MainActivity's onCreate() method so that it will set up the windowed app when it is suppose to.
Code:
/**
* Called when the activity is first created to set up all of the features.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
// If the user is in the PopupMainActivity function, the setUpWindow function would be called from that class
// otherwise it would call the function from this class that has no implementation.
setUpWindow();
// Make sure to set your content view AFTER you have set up the window or it will crash.
setContentView(R.layout.main);
// Again, this will call either the function from this class or the PopupMainActivity one,
// depending on where the user is
setUpButton();
}
As you can see from the code, I called this method before i set the content view for the activity. This is very important, otherwise you will get a runtime exception and the app will crash every time.
After you are done with that, you have successfully set up a program that will change from a windowed state to a full app state depending on which class is called. For example, if you set up an intent to open the floating window app, it would look something like this:
Code:
Intent window = new Intent(context, com.klinker.android.floating_window.PopupMainActivity.class);
window.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(window);
You are still able to call the MainActivity class like you normally would then. with an intent like this:
Code:
Intent fullApp = new Intent(context, MainActivity.class);
fullApp.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(fullApp);
That is just about it, obviously my solution and demo are very simple implementations of what it can do. You can see from the demo app that I simply go back and forth between the activities with a button, then i have an edittext at the bottom to demonstrate how the window resizes.
You can literally do anything with this though. It will work with any layouts you have set up and is a very cool way for your users to experience your app in a different light. If you want to change how something works in the popup part of the app, all you have to do is function that portion of code out, then override that method from the popup activity, so the possibilities are endless with what can be done here.
Credit for this goes to the Paranoid Android team of course for inspiring the idea, then Jacob Klinker (klinkdawg) and myself (Luke Klinker) for the implementation without framework tweaks or custom roms. This should work for any users, no matter the phone, android version, or custom rom.
I honestly have no clue if it will work on anything below 4.0, but if you test and find out, sound off in the comments!
Thanks and enjoy! I hope to see lots of dynamic and awesome popups in the future because it really is just that simple, it won't take you more than a half hour to get this working!
Click to expand...
Click to collapse
Original Thread : http://forum.xda-developers.com/showthread.php?t=2488094
This article is originally from HUAWEI Developer Forum
Forum link: https://forums.developer.huawei.com/forumPortal/en/homeExperiment your ideas, make your changes in website/Applications, AB Testing analytics will help you find which experiment results better conversion rate optimization.
Introduction
A/B Testing (also known as Split Testing), A/B testing is a fantastic method for find out the best online advertisement and marketing strategies. designers are using it at this very moment to obtain valuable insight regarding visitor behavior and to improve applications or website conversion rate.
A/B testing involves sending half your users to one version of a page, and the other half to another, and watching the analytics to see which one is more effective in getting them to do what you want them to do (for example, sign up for a user account), this helps you make reach more audience.
Implementation Process
1. Enabling A/B Testing, Access dependent service
2. Create an experiment
3. Manage an experiment
Enabling A/B Testing
· Create sample application in android and configure into AGC.
· Enable Push service and Analytics
· Open AGC select sample project Growing->A/B testing Now enable A/B testing.
After enabling service, you will get options
· Create notifications experiment.
· Create remote configuration experiment.
Creating an Experiment
Create Remote Configuration Experiment
The best way to implement new feature or an updated user experience, based on user response you can implement features. follow below steps.
Click create remote configuration experiment you will get below screen
{
"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"
}
Open AGC -> select project->Growing->Remote Configuration enable service
Now open A/B Testing tab.
Declare name and description then click Next Button.
· In target user page, set filter conditions, select target user ratio.
· Click Conditions and select one of the following filter conditions.
Version: Select the version of the app.
Language: Select the language of the device
Country/Region: Select the country or region where the device is located.
Audience: Select the audience of HUAWEI Analytics Kit.
User attributes: Select the user attributes of HUAWEI Analytics Kit
After the setting is complete, click Next.
· Create Treatment & Control Groups
To add multiple parameters using new parameter option.
To add multiple treatment group using New treatment group option.
You can create customize parameter names.
· After filling all details done, click next button.
· Create Track Indicators
Select main and optional indicators, then save all details
· After saving all details you will get below screen.
· After experiment created you can follow below steps.
Test the experiment
Start the experiment
View the report
Increase the percentage of users who participate in the experiment.
Release the experiment
Test an Experiment
Before starting an experiment, you need to test individually.
· Generate AAID
· Using Add test user and add an AAID of a test user.
· Run your app on the test user device and ensure that the test user can receive information.
· Follow below step to generate AAID.
Code:
private fun getAAID() {
var inst = HmsInstanceId.getInstance(this)
val aaid = inst.id
txtAaid.text=aaid
Log.d("AAID", "getAAID success:$aaid")
}
Starting an experiment
· Click Start operation column and click OK
Viewing an Experiment Report
· You can view experiment reports in any state. The system also provides the following information for each indicator by default
· Increment: The system compares the indicator value of the treatment group with that of the control group to measure the improvement of the indicator.
· Other related indicators: For example, for Retention rate after 1 day, the system also provides data about Retained users.
Releasing an Experiment
· Click Release in the operation column
· Select treatment group set condition name.
· Click Go to Remote configuration button.it will redirect new page.
· If you want modify any parameter values. click operation choose Edit option to modify values, Click Save Button.
Let’s do Code
· Setting Default In-app Parameter Values
Code:
val config = AGConnectConfig.getInstance()
val map: MutableMap<String, Any> = HashMap()
map["test1"] = "test1"
map["test2"] = "true"
config.applyDefault(map)
· Fetching Parameter Values from Remote Configuration
· You can call the fetch API to obtain parameter values from Remote Configuration in asynchronous mode.
· After the API is successfully called, data of the ConfigValues type is returned from Remote Configuration.
· After obtaining parameter value updates, the app calls the apply() method
· Calling the fetch() method within an interval will obtain locally cached data instead of obtaining data from the cloud.
· We can customize the fetch interval
Loading Process
· Applying parameter values Immediately.
Code:
config.fetch()
.addOnSuccessListener { configValues ->
config.apply(configValues)
}
.addOnFailureListener { error ->
Log.d("TAG", error.message)
}
· Applying parameter values upon the next startup
You can fetch parameter values at any time, in this case latest parameter values can be applied without asynchronous waiting.
Code:
val last = config.loadLastFetched()
config.apply(last)
config.fetch()
.addOnSuccessListener {
}
.addOnFailureListener { error ->
Log.d("TAG", error.message)
}
}
Report
Conclusion:
A/B testing which was earlier used mostly on e-commerce portals and websites has now been introduced for Android apps as well. This form of testing was found to be highly effective for the developers.
So, that's how to implement an A/B Testing in your next app.
Any questions about this, you can try to acquire answers from HUAWEI Developer Forum.
More information like this, you can visit HUAWEI Developer Forum
Introduction
Online food ordering is process to deliver food from restaurants. In this article will do how to Integrate Analytics, App-Messaging in food applications.
Steps
1. Create App in Android.
2. Configure App in AGC.
3. Integrate the SDK in our new Android project.
4. Integrate the dependencies.
5. Sync project.
Analytics Module
Huawei Analytics will helps to understand how people using mobile application. Analytics model help you gain a deeper insight into your user, products and contents.
1. Collect and report custom events.
2. Set a maximum of 25 user attributes
3. Automate event collection and session calculation with predefined event ID’s and parameter.
Use Cases
1. Analyze user behaviour using both predefined and custom events.
2. Use audience building to tailor your marketing activity to your users’ behaviour and preferences.
3. Use dashboards and analytics to measure your marketing activity and identify areas to improve.
Function Restrictions
Device restrictions: The following automatically collected events of analytics kit depend on HMS Core (APK). Therefore, which are not supported on third-party devices where HMS Core is not installed including but not limited to Oppo, Vivo, Xiaomi, Samsung and Oneplus.
Event quantity restriction: Each app can analyze a maximum of 500 events.
Event parameter restrictions: You can define a maximum of 25 parameters for each event, and maximum of 100 event parameter for each app.
AGC Configuration
1. Create an app adding an app to the project.
2. Enable Analytics Choose My Projects> Huawei Analytics
{
"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"
}
3. Enable Analytics API Choose My Projects > Project settings > Manage APIs
Integration
Create Application in Android Studio.
App level gradle dependencies.
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
Gradle dependencies
Code:
implementation 'com.huawei.hms:hianalytics:5.0.3.300'
Root level gradle dependencies
Code:
maven {url 'https://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.3.1.300'
1. Create Instance for HiAnalyticsInstance in the onCreate method
Code:
HiAnalyticsTools.enableLog();
HiAnalyticsInstance instance = HiAnalytics.getInstance(this);
2. Create method for report an event.
Code:
private void reportevent() {
Bundle bundle = new Bundle();
bundle.putString("Name", signInResult.getUser().getDisplayName());
mInstance.onEvent("SIGNIN", bundle);
}
Output
App Messaging Module
Huawei App messaging is one of the power full tool to promote information to audience. This will help when you are trying to get more attention to your application. We can target active users to encourage them to use this app.
App Messaging allows to customize your messages visuals and the way they will be sent, and define events for triggering message sending to your users at the right moment.
Message Types
1. Pop-up Message: Title, body and contain an image, and up to two buttons.
2. Banner Message: Message is displayed on top of the screen, containing a thumbnail and the message title and body. user can tap the banner to access specified page.
3. Image: It contains only image. An image message can be a poster well designed to promote an activity. User can tap the image to access the activity details.
AGC Configuration
1. Enable App Messaging Api Choose My Projects > Project settings > Manage APIs
2. Enable App Messaging Choose My Projects > Growing > App Messaging Click Enable Now.
3. Click New button and enter the required information.
4. Enter required details, and then click Next button.
5. In Select Sending Target node, click New condition for matching target users.
Select conditions in Select drop-down, and then click Next
6. In Set Sending Time node, select Started and Ended drop-downs.
Select required options in Trigger event and Frequency limit, and then click Next
7. Once all the required information filled, and then click Save button
8. Navigate to Operation tab, and then click Test option to perform the App Messaging publishing
Integration
Gradle dependencies
Code:
implementation 'com.huawei.agconnect:agconnect-appmessaging:1.4.0.300'
1. Generate AAID, this AAID will help you to sending App-Messages.
Code:
private void generateAAID(){
HmsInstanceId inst = HmsInstanceId.getInstance(this);
Task<AAIDResult> idResult = inst.getAAID();
idResult.addOnSuccessListener(aaidResult -> Log.d("AAID", "getAAID success:" + aaidResult.getId() ))
.addOnFailureListener(e -> Log.d("AAID", "getAAID failure:" + e));
}
2. For displaying messages we need to call AGConnectAppMessaging Instance.
3. setFetchMessageEnable() To allow data synchronization from the app gallery connect server.
4. setDisplayEnable() To Enable message display.
5. setForceFetch() To specify that the in-app message data must be obtained from App Gallery connect server.
Code:
private void initializeInAppMessage(){
AGConnectAppMessaging appMessaging = AGConnectAppMessaging.getInstance();
appMessaging.setFetchMessageEnable(true);
appMessaging.setDisplayEnable(true);
appMessaging.setForceFetch();
}
Result:
Conclusion
In this Article, I have explained how to integrate App Messaging and Analytics Kit on food application.
Reference:
Analytics kit:
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/introduction-0000001050745149
App Messaging:
https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agc-appmessage-introduction
{
"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"
}
Nowadays, apps use device location to provide a wide variety of services. You may want to see a user's location to show services around them, learn the habits of users in different areas, or perform location-based actions, like a ride-hailing app calculating travel distance and trip fare.
In order to protect user privacy, however, most apps request device location only when they run in the foreground. Once switched to the background, or even with the device screen turned off, apps are usually not allowed to request device location. As a result, they cannot record the GPS track of a device, which negatively affects the user experience of core functions of many apps, such as ride-hailing, trip-sharing, and exercise, all of which need to track location in real time.
To ensure this kind of app is able to function properly, the app developer usually needs to give their app the capability to obtain device location when the app is running in the background. So, is there a service which the app can use to continuously request device location in the background? Fortunately, HMS Core Location Kit offers the background location function necessary to do just that.
In this article, I'll show you how to use the background location function to request device location continuously in the background.
Background Location Implementation Method
An app is running on a non-Huawei phone with the location function enabled for the app using LocationCallback. After the app is switched to the background, it will be unable to request device location.
To enable the app to continuously request device location after it is switched to the background, the app developer can use the enableBackgroundLocation method to create a foreground service. This increases the frequency with which the app requests location updates in the background. The foreground service is the most important thing for enabling successful background location because it is a service with the highest priority and the lowest probability of being ended by the system.
Note that the background location function itself cannot request device location. It needs to be used together with the location function enabled using LocationCallback. Location data needs to be obtained using the onLocationResult(LocationResult locationResult) method in the LocationCallback object.
Background Location Notes
1. The app needs to be running on a non-Huawei phone.
2. The app must be granted permission to always obtain device location.
3. The app must not be frozen by the power saving app on the device. For example, on a vivo phone, you need to allow the app to consume power when running in the background.
Demo Testing Notes
1. It is recommended not to charge the device during the test. This is because the app may not be limited for power consumption while the device is charging.
2. To determine if the app is requesting device location, you can check whether the positioning icon is displayed in the device's status bar. On vivo, for example, the phone will show a positioning icon in the status bar when an app requests the phone's location. If background location is disabled for the app, the positioning icon in the status bar will disappear after the app is switched to the background. If background location is enabled for the app, however, the phone will continue to show the positioning icon in the status bar after the app is switched to the background.
Development Preparation
Before getting started with the development, you will need to integrate the Location SDK into your app. If you are using Android Studio, you can integrate the SDK via the Maven repository.
Here, I won't be describing how to integrate the SDK. You can click here to learn about the details.
Background Location Development Procedure
After integrating the SDK, perform the following steps to use the background location function:
1. Declare the background location permission in the AndroidManifest.xml file.
Code:
<service
android:name="com.huawei.location.service.BackGroundService"
android:foregroundServiceType="location" />
Generally, there are three location permissions in Android:
ACCESS_COARSE_LOCATION: This is the approximate location permission, which allows an app to obtain an approximate location, accurate to city block level.
ACCESS_FINE_LOCATION: This is the precise location permission, which allows an app to obtain a precise location, more accurate than the one obtained based on the ACCESS_COARSE_LOCATION permission.
ACCESS_BACKGROUND_LOCATION: This is the background location permission, which allows an app to obtain device location when running in the background in Android 10. In Android 10 or later, this permission is a dangerous permission and needs to be dynamically applied for. In versions earlier than Android 10, an app can obtain device location regardless of whether it runs in the foreground or background, as long as it is assigned the ACCESS_COARSE_LOCATION permission.
In Android 11 or later, these three permissions cannot be dynamically applied for at the same time. The ACCESS_BACKGROUND_LOCATION permission can only be applied for after the ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION permissions are granted.
2. Declare the FOREGROUND_SERVICE permission in the AndroidManifest.xml file to ensure that the background location permission can be used properly.
Note that this step is required only for Android 9 or later. As I mentioned earlier, the foreground service has the highest priority and the lowest probability of being ended by the system. This is a basis for successful background location.
Code:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
3. Create a Notification object.
Code:
public class NotificationUtil {
public static final int NOTIFICATION_ID = 1;
public static Notification getNotification(Context context) {
Notification.Builder builder;
Notification notification;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
String channelId = context.getPackageName();
NotificationChannel notificationChannel =
new NotificationChannel(channelId, "LOCATION", NotificationManager.IMPORTANCE_LOW);
notificationManager.createNotificationChannel(notificationChannel);
builder = new Notification.Builder(context, channelId);
} else {
builder = new Notification.Builder(context);
}
builder.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Location SDK")
.setContentText("Running in the background ")
.setWhen(System.currentTimeMillis());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
notification = builder.build();
} else {
notification = builder.getNotification();
}
return notification;
}
}
4. Initialize the FusedLocationProviderClient object.
Code:
FusedLocationProviderClient mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
5. Enable the background location function.
Code:
private void enableBackgroundLocation() {
mFusedLocationProviderClient
.enableBackgroundLocation(NotificationUtil.NOTIFICATION_ID, NotificationUtil.getNotification(this))
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
LocationLog.i(TAG, "enableBackgroundLocation onSuccess");
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
LocationLog.e(TAG, "enableBackgroundLocation onFailure:" + e.getMessage());
}
});
}
Congratulations, your app is now able to request device location when running in the background.
Conclusion
With the booming of mobile Internet, mobile apps have been playing a more and more important role in our daily lives. Many apps now offer location-based services to create a better user experience. However, most apps can request device location only when they run in the foreground, in order to protect user privacy. To ensure this kind of app functions properly, it is necessary for the app to receive location information while it is running in the background or the device screen is off.
My app can now just do that easily, thanks to the background location capability in Location Kit. If you want your app to do the same, have a try on this capability and you may be surprised.
Question 1
When my app accesses a material (such as a sticker) for a user, my app displays a message indicating that the access failed due to a network error and prompting the user to try again.
When my app uses an AI capability, the following information was displayed in my app's logs: errorCode:20124 errorMsg:Method not Allowed.
Solution
1. Check whether you have configured your app authentication information. If not, do so by following step 1 in the development guide.
2. Check whether you have enabled Video Editor Kit for your app. If not, enable the service either on HUAWEI Developers or in AppGallery Connect. After the service is enabled, due to factors such as network caches, it will take some time for the service to take effect for your app.
3. Check whether the signing certificate fingerprint in the Android Studio project code of your app is consistent with that configured in AppGallery Connect. If not, or you have not configured the fingerprint in the project code or AppGallery Connect, configure the fingerprint by following the instructions here. After you configure the fingerprint, due to factors such as network caches, it will take some time for the fingerprint to take effect for your app.
4. Check whether you have allocated the material in question.
5. Check whether you have applied for the AI capability you want.
If the problem persists, submit a ticket online (including your detailed logs and app ID) for troubleshooting.
Question 2
After my app obtains a material column, the column name was either 101 or blank in my app.
Solution
1. Sign in to AppGallery Connect and select your desired project. In the navigation pane on the left, go to Grow > Video Editor Kit > App content operations > Column manager.
{
"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"
}
2. Click Delete columns.
3. Click Initialize columns.
4. Uninstall and then install the app.
Question 3
When my app uses the AI filter of the fundamental capability SDK, my app receives no callback, and the Logcat window in Android Studio displays the following information: E/HVEExclusiveFilter: Failed resolution of: Lcom/huawei/hms/videoeditor/ai/imageedit/AIImageEditAnalyzerSetting$Factory;.
Cause
You did not add the dependencies necessary for the AI filter capability.
Solution
Add the following dependencies on the AI filter capability:
Code:
// Dependencies on the AI filter capability.
implementation 'com.huawei.hms:video-editor-ai-common:1.9.0.300'
implementation 'com.huawei.hms:video-editor-ai-imageedit:1.3.0.300'
implementation 'com.huawei.hms:video-editor-ai-imageedit-model:1.3.0.300'
Click here for more details.
Question 4
My app is integrated with the fundamental capability SDK. After a video asset was added to the corresponding lane, my app called getSize or getPosition but obtained a null value.
Cause
When the getSize or getPosition method is called, the calculation of the video position in the preview area is not completed.
Solution
After adding a video asset to the lane, call seekTimeLine of HuaweiVideoEditor to begin calculation of the video position in the preview area. Calling seekTimeLine is an asynchronous operation. In its callback, you can obtain or set the size and position of an asset.
Below is an example:
Code:
// Specify the position of an asset on the preview area before adding the asset.
HuaweiVideoEditor.setDisplay(videoContentLayout);
Click here for more details.
Code:
// Add a video asset to the video lane.
HVEVideoAsset mHveVideoAsset= hveVideoLane.appendVideoAsset(sourceFile.getAbsolutePath());
mEditor.seekTimeLine(0, new HuaweiVideoEditor.SeekCallback() {
@Override
public void onSeekFinished() {
Log.d(TAG, "onSeekFinished: size:" + mHveVideoAsset.getSize() + ", position: " + mHveVideoAsset.getPosition()); }
});
References
HMS Core Video Editor Kit home page
Development Guide of HMS Core Video Editor Kit