Android using native and java activity in the same app - Android Q&A, Help & Troubleshooting

Is it possible to have mix of native and regular activity in the same app? I have a scenario where some GUI handling needs to be done with a c++ native library.
Android documentation "Sample: native-activity" shows how to write a full native activity but how do i add it to an existing android app. If its possible how to invoke the native activity ?
I followed the steps in the documentation and added a new native activity (everything except not as main activity) but couldnt find a way launch it from java as the intent is looking for a class object.

Related

Integrating website's users' data to Android app

Hello guys,
I want to make an app which gets its data from a live website (not exists yet). So decided to use Wordpress and fetch the data via REST JSON API which would be available through this Wordpress plugin: http://goo.gl/7Qfccc
But I'm wondering how to integrate users' info and preserve ACL (access control list) for authorized access to some app's data as will be on the Wordpress site.
Using Parse API sounds promising, but I have no idea if it's possible to handle only user section by Parse and integrate it with Wordpress' content and ACL system. Or even I could Parse alone as the whole solution.
Thanks

How to identify requests from quick apps on an HTML5 page

How to identify requests from quick apps on an HTML5 page so that the service logic will not instruct users to download an app?
The web component of a quick app uses the same standard HTML execution environment as browsers such as Google Chrome and Safari. When an HTML5 web page is loaded, the User-Agent attribute is reported to the server. The HTML5 web page can obtain the User-Agent object of the current execution environment through the JavaScript function. Therefore, you can set the User-Agent attribute for the web component to identity requests from quick apps.
The implementation procedure is as follows:
1. In the quick app, set the User-Agent attribute of the web component to default.
Code:
<web id='web' src="{{websrc}}" allowthirdpartycookies="true" useragent="default"></web>
2. On the HTML5 page, check whether the window.navigator.userAgent object contains the hap keyword. If yes, the request is from a quick app.
Code:
if (window.navigator.userAgent.indexOf("hap") >= 0) {
// The request comes from a quick app.
}
For details about Huawei developers and HMS, visit the website.
https://forums.developer.huawei.com/forumPortal/en/home?fid=0101246461018590361

How Can I Integrate HUAWEI Ads into a Huawei HTML5 Quick Game?

Symptom:
Currently, no ad API is provided for an HTML5 quick game. How can I integrate HUAWEI Ads into my quick game?
Analysis:
Currently, HUAWEI Ads supports only quick apps and runtime quick games, but not HTML5 quick games. You can use a two-way communication mechanism between the web component on the UX page of a quick game and the HTML5 web page of the game to integrate HUAWEI Ads into an HTML5 quick game. The onMessage lifecycle function on the UX page receives messages from an HTML5 page, calls the ad API of quick apps to obtain ad information (only available for native ads and rewarded video ads), and sends the obtained ad information to the HTML5 page through this.$element(‘web’).postMessage({ message: JSON.stringify(result) });.
Solution:
It is recommended that the ad creation and ad API request processes be separately encapsulated in different functions, instead together in the onInit or onMessage lifecycle function. This is because the onInit function is called during page initialization, which implements quicker loading, but it is not suitable for processing complex logic; the onMessage function is used to receive character strings passed by HTML5 pages. After you add a judgment branch, the corresponding function is called to perform specific ad processing.
Note: Currently, the quick app framework supports the creation of ad objects only in the onInit function, but not in functions such as onMessage. Keep the position of the code block unchanged.
For more sample code, you can refer to this site.
https://gist.github.com/Mayism/0a9f12438da0e86f06594e01e7643895
For more FAQs and cases about HUAWEI Ads integration, visit the following link:
https://developer.huawei.com/consumer/en/doc/development/quickApp-Guides/quickapp-access-ads-kit

How a Background Remover Is Born

Why Do I Need a Background Remover​A background removal tool is not really a new feature, but rather its importance has grown as the world shifted over to online working and learning over the last few years. And I did not find how important this tool could be until just two weeks ago. On a warm, sunny morning with a coffee on hand, I joined an online conference. During this conference, one of my colleagues pointed out to me that they could see my untidy desk and an overflowing bin in the background. Naturally, this left me feeling embarrassed. I just wish I could travel back in time to use a background remover.
Now, I cannot travel in time, but I can certainly create a background removal tool. So, with this new-found motive, I looked online for some solutions and came across the body or head segmentation capability from HMS Core Video Editor Kit, and developed a demo app with it.
This service can divide the body or head from an input image or video and then generate a video, an image, or a sticker of the divided part. In this way, the body or head segmentation service helps realize the background removal effect.
Now, let's go deeper into the technical details about the service.
How the Background Remover Is Implemented​The algorithm of the service performs a series of operations on the input video, including extracting frames, using an AI model to process the video, and encoding. Among all these, the core is the AI model. How a service performs is affected by factors like device computing power and power consumption. Considering these, the development team of the service manages to equip it with a light-weight AI model that does a good job in feature extraction, by taking measures like compression, quantization, and pruning. In this way, the processing duration of the AI model is decreased to a relatively low level, without compromising the segmentation accuracy.
The mentioned algorithm supports both images and videos. An image takes the algorithm a single inference for the segmentation result. A video is actually a collection of images. If a model features poor segmentation capability, the segmentation accuracy for each image will be low. As a result, the segmentation results of consecutive images will be different from each other, and the segmentation result of the whole video will appear shaking. To resolve this, the team adopts technologies like inter-frame stabilization and the objective function for inter-frame consistency. Such measures do not compromise the model inference speed yet fully utilize the time sequence information of a video. Consequently, the algorithm sees its inter-frame stabilization improved, which contributes to an ideal segmentation effect.
By the way, the service requires that the input image or video contains up to 5 people whose contours should be visible. Besides, the service supports common motions of the people in the input image or video, like standing, lying, walking, sitting, and more.
The technical basics of the service conclude here, and let's see how it can be integrated with an app.
How to Equip an App with the Background Remover Functionality​Preparations​Go to AppGallery Connect and configure the app's details. In this step, we need to register a developer account, create an app, generate a signing certificate fingerprint, and activate the required services.
Integrate the HMS Core SDK.
Configure the obfuscation scripts.
Declare necessary permissions.
Setting Up a Video Editing Project​Prerequisites​1. Set the app authentication information either by:
Using an access token: Call the setAccessToken method to set an access token when the app is started. The access token needs to be set only once.
Code:
MediaApplication.getInstance().setAccessToken("your access token");
Using an API key: Call the setApiKey method to set an API key when the app is started. The API key needs to be set only once.
Code:
MediaApplication.getInstance().setApiKey("your ApiKey");
2. Set a License ID. The ID is used to manage the usage quotas of the kit, so make sure the ID is unique.
Code:
MediaApplication.getInstance().setLicenseId("License ID");
Initializing the Runtime Environment for the Entry Class​A HuaweiVideoEditor object serves as the entry class of a whole video editing project. The lifecycle of this object and the project should be the same. Therefore, when creating a video editing project, create a HuaweiVideoEditor object first and then initialize its runtime environment. Remember to release this object when exiting the project.
1. Create a HuaweiVideoEditor object.
Code:
HuaweiVideoEditor editor = HuaweiVideoEditor.create(getApplicationContext());
2. Determine the preview area position.
This area renders video images, a process that is implemented by creating SurfaceView within the SDK. Make sure that the position of this area is specified before the area is created.
Code:
<LinearLayout
android:id="@+id/video_content_layout"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="@color/video_edit_main_bg_color"
android:gravity="center"
android:orientation="vertical" />
// Specify the preview area position.
LinearLayout mSdkPreviewContainer = view.findViewById(R.id.video_content_layout);
// Specify the layout of the preview area.
editor.setDisplay(mSdkPreviewContainer);
3. Initialize the runtime environment of HuaweiVideoEditor. LicenseException will be reported when the license verification fails.
The HuaweiVideoEditor object, after being created, has not occupied any system resources. We need to manually set the time for initializing its runtime environment, and then the necessary threads and timers will be created in the SDK.
Code:
try {
editor.initEnvironment();
} catch (LicenseException error) {
SmartLog.e(TAG, "initEnvironment failed: " + error.getErrorMsg());
finish();
return;
}
Integrating the Segmentation Capability​
Code:
// Initialize the segmentation engine. segPart indicates the segmentation type, whose value is an integer. Value 1 indicates body segmentation, and a value other than 1 indicates head segmentation.
visibleAsset.initBodySegEngine(segPart, new HVEAIInitialCallback() {
@Override
public void onProgress(int progress) {
// Callback when the initialization progress is received.
}
@Override
public void onSuccess() {
// Callback when the initialization is successful.
}
@Override
public void onError(int errorCode, String errorMessage) {
// Callback when the initialization failed.
}
});
// After the initialization is successful, apply the segmentation effect.
visibleAsset.addBodySegEffect(new HVEAIProcessCallback() {
@Override
public void onProgress(int progress) {
// Callback when the application progress is received.
}
@Override
public void onSuccess() {
// Callback when the effect is successfully applied.
}
@Override
public void onError(int errorCode, String errorMsg) {
// Callback when the effect failed to be applied.
}
});
// Stop applying the segmentation effect.
visibleAsset.interruptBodySegEffect();
// Remove the segmentation effect.
visibleAsset.removeBodySegEffect();
// Release the segmentation engine.
visibleAsset.releaseBodySegEngine();
And now the app is capable of removing the image or video background.
This function is ideal for e-conferencing apps, where the background is not important. For learning apps, it allows teachers to change the background to the theme of the lesson, for better immersion. Not only that, but when it's used in a short video app, users can put themselves in unusual backgrounds, such as space and the sea, to create fun and fantasy-themed videos.
Have you got any better ideas of how to use the background remover? Let us know in the comments section below.
Wrap up​Background removal tools are trending among apps in different fields, given that such a tool helps images and videos look better by removing unnecessary or messy backgrounds, as well as protecting user privacy.
The body or head segmentation service from Video Editor Kit is one such solution for removing a background. It supports both images and videos, and outputs a video, an image, or a sticker of the segmented part for further editing. Its streamlined integration makes it a perfect choice for enhancing videos and images.

How to Target Ads Precisely While Protecting User Privacy

Background​
When using an app, if pop-up ads keep appearing when we browse app pages but we are not interested in the advertised content, not only will our browsing experience be negatively affected, but we will also quickly become tired of the advertised content. Unwanted ads are usually annoying. Aimless ad targeting and delivery will result in the wrong ads being sent to users and cause poor ad performance.
So, as publishers, how do we guarantee that we can deliver ads to audiences who will be interested in them and how can we decrease users' resistance to advertising? The answer is to collect information about the user requirements of your target audiences or to really know them, and to do so in a way that causes the least annoyance. But when a user is unwilling to share their personal data, such as age, gender, and interests, with my app, placing an ad based on the page that the user is browsing is a good alternative.
For example, a user is reading an article in a news app about the fast-paced development of electric vehicles, rapidly improving battery technology, and the expansion of charging stations in cities. If the targeted advertising mechanism understands the context of the article, when users continue to read news articles in the app, they may see native ads from nearby car dealerships for test driving electric vehicles or ads about special offers for purchasing electric vehicles of a certain brand. In this way, user interests can be accurately discovered, and publishers can perform advertising based on the keywords and other metadata included in the contextual information of the app page, or any other content users are reading or watching, without having to collect users' personal information.
But I can't integrate these features all by myself, so I started searching for tools to help me request and deliver ads based on the contextual information on an app page. That's when I had the great fortune to discover Ads Kit of HMS Core. Ads Kit supports personalized and non-personalized ads. Personalized ad requests require users to grant the app access to some of their personal information, which may not be palatable for some users. Non-personalized advertising, however, is not constrained by this requirement.
Non-personalized ads are not based on users' past behavior. Instead, they target audiences using contextual information. The contextual information includes the user's rough geographical location (such as city) authorized by the user, basic device information (such as the mobile phone model), and content of the current app or search keyword. When a user browses a piece of content in your app, or searches for a topic or keyword to express a specific interest, the contextual ad system scans a specific word or a combination of words, and pushes an ad based on the page content that the user is browsing.
Today, data security and personal privacy requirements are becoming more and more stringent. Many users are very hesitant to provide personal information, which means that precise ad delivery is becoming harder and harder to achieve. Luckily, Ads Kit requests ads based on contextual information, enabling publishers to perform ad delivery with a high degree of accuracy while protecting user privacy and information.
Now let's take a look at the simple steps we need to perform in order to quickly integrate Ads Kit and perform contextual advertising.
Integration Steps​
1. Ensure that the following prerequisites are met before you integrate the Ads Kit:
HMS Core (APK) 4.0.0.300 or later should be installed on devices. If the APK is not installed or an earlier version has been installed, you will not be able to call the APIs of the Ads Kit.
Before you begin the integration process, make sure that you have registered as a Huawei developer and completed identity verification on HUAWEI Developers.
Create a project and add an app to the project for later SDK integration.
2. Import the Ads SDK.
You can integrate the Ads SDK using the Maven repository.
That is, before you start developing an app, configure the Maven repository address for Ads SDK integration in your Android Studio project.
The procedure for configuring the Maven repository address in Android Studio is different for Gradle plugin versions earlier than 7.0, Gradle plugin 7.0, and Gradle plugin versions 7.1 and later. Configure the Maven repository address accordingly based on your Gadle plugin version.
3. Configure network permissions.
To allow apps to use cleartext HTTP and HTTPS traffic on devices with targetSdkVersion 28 or later, configure the following information in the AndroidManifest.xml file:
Code:
<application
...
android:usesCleartextTraffic="true"
>
...
</application>
4. Configure obfuscation scripts.
Before building the APK, configure the obfuscation configuration file to prevent the SDK from being obfuscated.
Open the obfuscation configuration file proguard-rules.pro in your app's module directory of your Android project, and add configurations to exclude the SDK from obfuscation.
Code:
-keep class com.huawei.openalliance.ad.** { *; }
-keep class com.huawei.hms.ads.** { *; }
5. Initialize the SDK.
You can initialize the SDK in the activity, or initialize the SDK by calling the HwAds.init(Context context) API in the AdSampleApplication class upon app launch. The latter method is recommended, but you have to implement the AdSampleApplication class by yourself.
6. Request ads based on contextual information.
The SDK provides the setContentBundle method in the AdParam.Builder class for you to pass contextual information in an ad request.
The sample code is as follows:
Code:
RewardAd rewardAd = new RewardAd(this, rewardId);
AdParam.Builder adParam = new AdParam.Builder();
String mediaContent = "{\"channelCategoryCode\":[\"TV series\"],\"title\":[\"Game of Thrones\"],\"tags\":[\"fantasy\"],\"relatedPeople\":[\"David Benioff\"],\"content\":[\"Nine noble families fight for control over the lands of Westeros.\"],\"contentID\":[\"123123\"],\"category\":[\"classics\"],\"subcategory\":[\"fantasy drama\"],\"thirdCategory\":[\"mystery\"]}\n";
adParam.setContentBundle(mediaContent);
rewardAd.loadAd(adParam.build(), new RewardAdLoadListener());
Conclusion​Nowadays, advertising is an important way for publishers to monetize their apps and content, and how to deliver the right ads to the right audiences has become a key focus point. In addition to creating high quality ads, significant efforts should be placed on ensuring precise ad delivery. As an app developer and publisher, I was always searching for methods to improve ad performance and content monetization in my app. In this article, I briefly introduced a useful tool, Ads Kit, which helps publishers request ads based on contextual information, without needing to collect users' personal information. What's more, the integration process is quick and easy and only involves a few simple steps. I'm sure you'll find it useful for improving your app's ad performance.
References​Development Guide of Ads Kit

Categories

Resources