Reference:
https://docs.unity.cn/cn/Packages-cn/[email protected]/manual/crash.html
1. Download Unity Hub.
2. Configure the Android environment in Unity Editor.
Choose Edit > Preferences > External Tools > Andriod and configure the JDK and SDK paths. You can keep the default paths.
Choose Edit > Project Settings > Player > Publish Settings. In the Build area, select items for Android as required.
{
"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. Import the HuaweiService package.
Download the package from Unity Assets Store.
In Unity Editor, choose Assets > Import package.
Select the required package and click Import. If you’re not sure which one to use, you can select all of them.
Completing Configurations in AppGallery Connect
1. Sign in to AppGallery Connect, and click the created app.
2. Go to My projects > Quality > Crash and click Enable now to enable the Crash service.
3. Go to Project settings > General information and download the latest agconnect-services.json file.
4. Save the file to the Assets\Plugins\Android directory of your Unity project.
Configuring the Project Information in Unity Editor
1. In Unity Editor, choose Edit > Project Settings > Player > Other Settings, and set the package name to match the package name you set in AppGallery Connect.
2. Add the following code to the project-level baseProjectTemplate.gradle file in the Assets\Plugins\Android directory:
XML:
allprojects {
buildscript {
repositories {
maven { url 'https://developer.huawei.com/repo/' }
}
dependencies {
classpath 'com.android.tools.build:gradle:3.6.0'
classpath 'com.huawei.agconnect:agcp:1.4.2.300'
}
}
repositories {
maven { url 'https://developer.huawei.com/repo/' }
}
}
3. Add the following code to the app-level LauncherTemplate.gradle file in the Assets\Plugins\Android directory:
XML:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
dependencies {
implementation 'com.huawei.hms:hianalytics:5.0.5.300'
implementation 'com.huawei.agconnect:agconnect-crash:1.4.2.300'
}
Integrating the Crash Service
1. In Unity Editor, choose GameObject > UI > Button and create a button. Click the button, click Add Component on the right to create a script file called testcrash, and then add the following methods:
C#:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using HuaweiService;
using HuaweiService.crash;
public class testcrash : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void CrashCollectON()
{
AGConnectCrash.getInstance().enableCrashCollection(true);
}
public void CrashCollectOFF()
{
AGConnectCrash.getInstance().enableCrashCollection(false);
}
public void SetTestIt()
{
Application.ForceCrash(0);
}
public void SetUserId()
{
AGConnectCrash.getInstance().setUserId("TestUser");
}
public void SetCustomKey()
{
AGConnectCrash.getInstance().setCustomKey("stringKey", "Hello world");
AGConnectCrash.getInstance().setCustomKey("booleanKey", false);
AGConnectCrash.getInstance().setCustomKey("doubleKey", 1.1);
AGConnectCrash.getInstance().setCustomKey("floatKey", 1.1f);
AGConnectCrash.getInstance().setCustomKey("intKey", 0);
AGConnectCrash.getInstance().setCustomKey("longKey", 11L);
}
public void SetDefaultlog()
{
AGConnectCrash.getInstance().log("set default log");
}
public void Setlog()
{
AGConnectCrash.getInstance().log(3, "set debug log");
AGConnectCrash.getInstance().log(4, "set info log");
AGConnectCrash.getInstance().log(5, "set warning log");
AGConnectCrash.getInstance().log(6, "set error log");
}
}
Keep creating other buttons and associating corresponding methods with them.
CrashCollectON:Enables crash data reporting.
CrashCollectOFFisables crash data reporting.
SetTestIt:Creates a crash.
SetCustomKey:Sets a custom key-value pair.
SetDefaultlog:Sets the default log level.
Setlog:Sets a custom log level.
SetUser:Sets a custom user ID.
2. Package the APK file and launch the app. Check whether the buttons have been successfully created.
Testing the API and Viewing the Crash Report
I have written about this part before. Please check out my previous post for details.
Generating and Uploading a Mapping File
Manual upload
1. Open the obfuscation script file for your Unity project.
2. Create the proguard-unity.txt and proguard-user.txt files and add the following code to prevent obfusaction:
XML:
-keepattributes *Annotation*
-keepattributes SourceFile,LineNumberTable
-keep public com.crashlytics.** { *; }
3. When the APK package is generated, the corresponding mapping file is automatically generated accordingly. You can then upload the mapping file to AppGallery Connect.
Auto upload
1. Enable the automatic upload of the mapping file.
Add the following code to the app-level LauncherTemplate.gradle file in the Assets\Plugins\Android directory:
XML:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
agcp{
mappingUpload = true
debug = true
appVersion = '0.1'
}
dependencies {
implementation 'com.huawei.hms:hianalytics:5.0.5.300'
implementation 'com.huawei.agconnect:agconnect-crash:1.4.2.300'
}
2. Export your Unity project and open it in Android Studio.
3. Generate a mapping file, which is automatically uploaded.
Run the gradle clean assembleRelease command or use Android Studio to install the app. The mapping file will be successfully generated.
The following code indicates that the upload is successful.
Restoring the Obfuscated Report
The following figure is a crash report when the obfuscation mapping file has not been uploaded.
This figure shows what the report looks like after being restored.
For more details, please refer to:
Crash sample code:
https://github.com/AppGalleryConnect/agc-demos/tree/main/Android/agc-crash-demo-java
Related
Introduction
Huawei Site Kit is a development kit for Android applications that provides location search functions like auto-completing keywords, searching for places and providing the details of places. With integrating of this kit into your application, you can search for a destination with keywords including location types like restaurants, hotels, hospitals and 500+ more, and provide detailed information including rating, address and phone number of the place.
You can benefit from Huawei Site Kit’s database by sending queries to its Web API. More than 130 million locations and its detailed information are accessible with easy to use API. All of these services and more is also supported in 13 languages, and 200+ countries.
{
"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"
}
Usecase
We will use Huawei site kit to search for nearby places based on query entered on search bar. Once we have nearby places, we will show them on Map.
To learn how to show places on Map, refer this article.
Prerequisites
1. Before installing Site Kit, you should have installed npm, Node.js, ionic CLI. To install ionic in system use below command.
Code:
npm install -g @ionic/cli
2. Generate a Signing Certificate Fingerprint. For generating the SHA key, refer this article.
3. Create an app in the Huawei AppGallery connect and enable Site Kit in Manage API section. Provide the SHA Key in App Information Section.
4. Provide storage location.
5. Download the agconnect-services.json.
Installation
1. Open windows CMD or terminal, and create ionic project.
Code:
ionic start Application_Name blank --type=angular
2. Download Cordova Site kit plugin. Navigate to your project root directory and install plugin using npm.
Code:
npm install <CORDOVA_SITE_KIT_PLUGIN_PATH>
3. Install @iONiC-native/core in your project for full ionic support with completion code.
Code:
npm install @ionic-native/core --save-dev
4. Copy the “node_modules\@hmscore\cordova-plugin-hms-map\ionic\dist\hms-map” folder to “node_modules/@iONiC-native” folder under your Ionic project.
5. Compile the project.
Code:
ionic build
npx cap init [appName] [appId]
where appId is package name.
6. After this command, you should add platform to the project. To add, follow command.
Code:
ionic capacitor add android
7. Add agconnect-services.json and signing certificate jks file to the app directory in your Android project as show below.
8. Add maven repository address and agconnect service dependencies in root level build.gradle.
Code:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
maven { url 'http://developer.huawei.com/repo/' }
}
dependencies {
classpath 'com.android.tools.build:gradle:3.6.1'
classpath 'com.google.gms:google-services:4.3.3'
classpath 'com.huawei.agconnect:agcp:1.4.0.300'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
apply from: "variables.gradle"
allprojects {
repositories {
google()
jcenter()
maven { url 'http://developer.huawei.com/repo/' } //This line is added by cordova-plugin-hms-account plugin
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
9. Add signing certificate configuration information in app-level build.gradle.
Code:
signingConfigs {
release {
storeFile file("mykeystore.jks") // Signing certificate.
storePassword "******" // KeyStore password.
keyAlias "******" // Alias.
keyPassword "******" // Key password.
v1SigningEnabled true
v2SigningEnabled true
}
}
10. Add plugin to the app-level build.gradle.
Code:
apply plugin: 'com.huawei.agconnect'
11. Add Site kit dependency in app-level build.gradle.
Code:
dependencies {
implementation 'com.huawei.hms:site:5.0.1.300'
}
12. Sync the project
Code:
npx capacitor sync
13. Import HmsSite in app_module.ts and add it in provider.
Code:
import {HmsSite} from '@ionic-native/hms-site/ngx';
providers: [
StatusBar,
HmsSite,
SplashScreen,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
]
More details, you can check https://forums.developer.huawei.com/forumPortal/en/topic/0204430607447740048
4. Gradle 4.6 and later
Steps to integrate service
1. We need to register as a developer account in AppGallery Connect
2. Create an app by referring to Creating a Project and Creating an App in the Project
3. Set the data storage location based on current location
4. Enabling Required Services: IAP Kit you will be asked to apply for Merchant service this process will take 2 days for review.
5. Enable settings In-app Purchases choose My Projects > Earn > In-App Purchases and click Settings.
6. Generating a Signing Certificate Fingerprint.
7. Configuring the Signing Certificate Fingerprint.
8. Get your agconnect-services.json file to the app root directory.
Development Process
Create Application in Android Studio.
1. Create Flutter project.
2. App level gradle dependencies. Choose inside project Android > app > build.gradle
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
Root level gradle dependencies
Code:
maven {url 'https://developer.huawei.com/repo/'}
classpath 'com.huawei.agconnect:agcp:1.4.1.300'3.
3. Add HMS IAP kit plugin download using below URL.
https://developer.huawei.com/consum...y-V1/flutter-sdk-download-0000001050727030-V1
4. On your Flutter project directory find and open your pubspec.yaml file and add library to dependencies to download the package from pub.dev. Or if you downloaded the package from the HUAWEI Developer website, specify the library path on your local device. For both ways, after running pub get command, the plugin will be ready to use.
Code:
name: mlsample
description: A new Flutter application.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
huawei_iap:
path: ../huawei_iap/
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
5. We can check the plugins under External Libraries directory.
6. Open main.dart file to create UI and business logics.
Configuring Product Info
To Add a product go to MyApps > DemoApp > Operate
{
"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"
}
Click Add Product Configure product information and click Save.
After the configuration is complete, Activate the product in the list to make it valid and purchasable.
Environment Check
Before calling any service you need to check user is login or not using IapClient.isEnvReady
Code:
environmentCheck() async {
isEnvReadyStatus = null;
try {
IsEnvReadyResult response = await IapClient.isEnvReady();
setState(() {
isEnvReadyStatus = response.status.statusMessage;
});
} on PlatformException catch (e) {
if (e.code == HmsIapResults.LOG_IN_ERROR.resultCode) {
_showToast(context, HmsIapResults.LOG_IN_ERROR.resultMessage);
} else {
_showToast(context, e.toString());
}
}
}
Fetch Product Info
We can fetch the product information of products using obtainProductInfo()
Note: The SkuIds is the same as that configured in AppGallery Connect.
Code:
loadConsumables() async {
try {
ProductInfoReq req = new ProductInfoReq();
req.priceType = IapClient.IN_APP_CONSUMABLE;
req.skuIds = ["SUB_30", "PR_6066"];
ProductInfoResult res = await IapClient.obtainProductInfo(req);
setState(() {
consumable = [];
for (int i = 0; i < res.productInfoList.length; i++) {
consumable.add(res.productInfoList[i]);
}
});
} on PlatformException catch (e) {
if (e.code == HmsIapResults.ORDER_HWID_NOT_LOGIN.resultCode) {
log(HmsIapResults.ORDER_HWID_NOT_LOGIN.resultMessage);
} else {
log(e.toString());
}
}
}
Purchase Result Info
When user click into buy button, first create purchase intent request and specify the type of the product and product ID in the request parameter.
If you want to test purchase functionality you need to create testing account. Using Sandbox testing we can do payment end-to-end functionality.
Once payment successfully done we get PurchaseResultInfo object, so this object has the details of the purchase.
Code:
subscribeProduct(String productID) async {
try {
PurchaseResultInfo result = await IapClient.createPurchaseIntent(
PurchaseIntentReq(
priceType: IapClient.IN_APP_CONSUMABLE, productId: productID));
if (result.returnCode == HmsIapResults.ORDER_STATE_SUCCESS.resultCode) {
log("Successfully plan subscribed");
} else {
log(result.errMsg);
}
} on PlatformException catch (e) {
if (e.code == HmsIapResults.ORDER_HWID_NOT_LOGIN.resultCode) {
log(HmsIapResults.ORDER_HWID_NOT_LOGIN.resultMessage);
} else {
log(e.toString());
}
}
}<strong><em><strong> </strong></em></strong>
For more, you can check https://forums.developer.huawei.com/forumPortal/en/topic/0204454642374170012
Introduction
In this article, we will learn how to convert image to document such as PPT or pdf format. As for users, it is inefficient to manually organize, edit, or improve the note-taking snapshots at conferences or images of paper documents.
Document converter enables apps to convert document images into electronic documents conveniently, such as PPT files. It can recognize documents and the texts in images, and return the recognized content to the client, which will restore the results into a PPT file.
How to integrate Document Converter
1. Configure the application on the AGC.
2. Apply for HiAI Engine Library.
3. Client application development process.
Configure application on the AGC
Follow the steps
Step 1: We need to register as a developer account in AppGallery Connect. If you are already a developer ignore this step.
Step 2: Create an app by referring to Creating a Project and Creating an App in the Project
Step 3: Set the data storage location based on the current location.
Step 4: Generating a Signing Certificate Fingerprint.
Step 5: Configuring the Signing Certificate Fingerprint.
Step 6: Download your agconnect-services.json file, paste it into the app root directory.
Apply for HiAI Engine Library
What is Huawei HiAI?
HiAI is Huawei’s AI computing platform. HUAWEI HiAI is a mobile terminal–oriented artificial intelligence (AI) computing platform that constructs three layers of ecology: service capability openness, application capability openness, and chip capability openness. The three-layer open platform that integrates terminals, chips, and the cloud brings more extraordinary experience for users and developers.
How to apply for HiAI Engine?
Follow the steps
Step 1: Navigate to this URL, choose App Service > Development and click HUAWEI HiAI.
{
"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"
}
Step 2: Click Apply for HUAWEI HiAI kit.
Step 3: Enter required information like Product name and Package name, click Next button.
Step 4: Verify the application details and click Submit button.
Step 5: Click the Download SDK button to open the SDK list.
Step 6: Unzip downloaded SDK and add into your android project under libs folder.
Step 7: Add jar files dependences into app build.gradle file.
implementation fileTree(include: ['*.aar', '*.jar'], dir: 'libs')
implementation 'com.google.code.gson:gson:2.8.6'
repositories {
flatDir {
dirs 'libs'
}
}Copy codeCopy code
Client application development process
Follow the steps.
Step 1: Create an Android application in the Android studio (Any IDE which is your favorite).
Step 2: Add the App level Gradle dependencies. Choose inside project Android > app > build.gradle.
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
Root level gradle dependencies.
Code:
maven { url 'https://developer.huawei.com/repo/' }
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
Step 3: Add permission in AndroidManifest.xml
XML:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
Step 4: Build application.
Request the runtime permission
Java:
private void requestPermissions() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int permission1 = ActivityCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
int permission2 = ActivityCompat.checkSelfPermission(this,
Manifest.permission.CAMERA);
if (permission1 != PackageManager.PERMISSION_GRANTED || permission2 != PackageManager
.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, 0x0010);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Java:
private void convertDocument() {
DocConverter docConverter = new DocConverter(this);//Construct Detector.
VisionImage image = VisionImage.fromBitmap(mBitmap);
VisionTextConfiguration config = new VisionTextConfiguration.Builder()
.setAppType(VisionTextConfiguration.APP_NORMAL)
.setProcessMode(VisionTextConfiguration.MODE_IN)
.setDetectType(TextDetectType.TYPE_TEXT_DETECT_FOCUS_SHOOT)
.setLanguage(VisionTextConfiguration.ENGLISH)
.build();
DocConverterConfiguration docConfig = new DocConverterConfiguration.Builder().build();
docConfig.setTextConfig(config);
MyCallBack cb = new MyCallBack();
int result_code = docConverter.detectSlide(image, cb);
}
class MyCallBack implements SlideCallback {
public void onDocDetect(DocCoordinates coor) {
Log.d("MainActivity", coor.toString());
}
public void onDocRefine(Bitmap bitmap) {
}
public void onSuperResolution(Bitmap bitmap) {
//Set super resolution image to image view
}
public void onTextRecognition(Text text) {
Log.d("MainActivity", text.getValue());
mTxtViewResult.setText(text.getValue());
}
public void onError(int errorCode) {
Log.d("MainActivity", "Error code: "+errorCode);
}
}
Result
Tips and Tricks
An image with a width ranging from 1080 pixels to 2560 pixels is recommended.
Multi-thread invoking is currently not supported.
If you are taking Video from a camera or gallery make sure your app has camera and storage permissions.
Add the downloaded huawei-hiai-vision-ove-10.0.4.307.aar, huawei-hiai-pdk-1.0.0.aar file to libs folder.
Check dependencies added properly.
Latest HMS Core APK is required.
Min SDK is 21. Otherwise you will get Manifest merge issue.
Conclusion
In this article, we have learnt what is the document convertor using Huawei HiAI using android and java. We have learnt how to convert the image to pdf. Huawei HiAI gives immense control on the text from image.
Reference
Document convertor
Apply for Huawei HiAI
Can we get the same content format of document after image is converted into text?
With the release of AppGallery Connect version 1.5.2 the Auth service now has full support for making use of unified sign-in with a Facebook account!
This new functionality makes AppGallery Connect Auth a great option for all of your app’s authentication needs both on Huawei devices and other Android devices.
So how do we go about using unified sign-in with a Facebook account? Let’s take a look!
Configuring the Facebook Login EnvironmentFirst, you’ll need to configure the Facebook Login environment.
Select or create a Facebook app.
{
"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"
}
Edit your resource file. Copy the following code to the /app/res/values/strings.xml file of your Android project.
Edit your manifest file. Add the following uses-permission element following the application element in the /app/manifest/AndroidManifest.xml file of your Android project.
Copy the following meta-data element to the application element.
Associate your package name and default activity class with your app and click Save. Confirm the use of this package name (skip this if your app has not been released on Google Play).
Develop a key hash using the following command, and release it for your app.
If you haven’t installed OpenSSL (openssl-for-windows) for your project, please go to Google Code Archive and download it as required.
keytool -exportcert -alias authdemounion -keystore F:\1.test\4.Auth\AuthDemo-Union\app\authdemounion.jks | openssl sha1 -binary | openssl base64
The command format is as follows:
keytool -exportcert -alias YOUR_RELEASE_KEY_ALIAS -keystore YOUR_RELEASE_KEY_PATH* | openssl sha1 -binary | openssl base64
The Facebook Login environment has now been successfully configured. Let’s move on to the operations relevant to Auth Service.
Enabling Auth ServiceSign in to AppGallery Connect, create a project and an app, and enable Auth Service. You’ll need to enter the App ID and App Secret for your app when enabling Facebook under Authentication modes, which can be found under Settings > Basic on Facebook for Developers. If they are not displayed, click the button following App Secret to show them.
Generating the Certificate Fingerprint for Your Android ProjectIf the demo project does not provide a Java KeyStore, go to Generate Signed Bundle or APK and click Create new.key store to create one
Generate an SHA-256 certificate fingerprint. Run the following command and enter the configured password to generate a SHA-256 certificate fingerprint.
keytool -list -v -keystore you_path\AuthDemo-Union\app\authdemounion.jks
Open the app-level build.gradle file, and configure the certificate information for your project
Click here to view the sample code.
Configure the generated SHA-256 certificate fingerprint in AppGallery Connect. (If you do not perform this step, error 6003 will be reported.)
Configure Your AppOpen the project-level build.gradle file and configure information, including the Maven repository address. The code is as follows:
Code:
buildscript {
repositories {
google()
jcenter()
maven { url 'http://developer.huawei.com/repo/' } // Configure this maven.
}
dependencies {
classpath "com.android.tools.build:gradle:4.1.1"
classpath 'com.huawei.agconnect:agcp:1.5.1.300' // Configure this path.
// NOTE: Do not copy your dependencies in here, which should be included
// in the build.gradle files of each module.
}
}
allprojects {
repositories {
google()
jcenter()
maven { url 'http://developer.huawei.com/repo/' } // Configure this maven.
}
}
Open the app-level build.gradle file and configure information, including the SDK information and app plug-in address. The code is as follows:
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect' // Configure the apply plug-in.
android {…}
dependencies {
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation "com.huawei.agconnect:agconnect-auth-facebook:1.5.2.201" // Configure this SDK.
implementation 'com.huawei.agconnect:agconnect-auth:1.5.2.201' // Configure this SDK.
}
Add the code for implementing unified sign-in:
Java:
private void FaceBookLogin(){
Log.i("AuthDemo", "start:" );
AGConnectAuth.getInstance().signIn(this, AGConnectAuthCredential.Facebook_Provider)
.addOnSuccessListener(new OnSuccessListener<SignInResult>() {
@Override
public void onSuccess(SignInResult signInResult) {
// onSuccess
AGConnectUser user = signInResult.getUser();
Log.i("AuthDemo", "success:" + user);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
// onFail
Log.i("AuthDemo", "failed:" + e.getMessage());
}
});
}
// Activity lifecycle required by the unified sign-in.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
AGConnectApi.getInstance().activityLifecycle().onActivityResult(requestCode, resultCode, data);
Viewing the Result and LogsOnce you run your signed APK on an Android phone and call the FaceBookLogin method, you’ll get the following page.
You can tap CONTINUE AS LINKING and sign in to your app with your Facebook account. The following log information will be displayed.
Compared with the traditional implementation mode, the unified sign-in has greatly simplified the development process. It is strongly recommended that you use the new mode.
For details about Auth Service, please refer to:
Auth Service document for Android
Guide for integrating Facebook account
Thanks for sharing.
Remote Configuration allows you to change how your app works and looks on the cloud, without requiring any app upgrades. Here we’ll take a look at a hands-on example of how to integrate Remote Configuration.
Enabling and Configuring Remote ConfigurationSign in to AppGallery Connect and click My projects.
Click your project card and select the app for which you want to enable Remote Configuration from the app drop-down list on the top.
Go to Grow > Remote Configuration. If this is your first time using Remote Configuration, click Use now in the upper right corner.
{
"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"
}
Then you’ll be able to configure the service in AppGallery Connect.
On the Remote Configuration page, set parameter and their conditions.
First, click New parameter to add a parameter. You can set multiple conditional values for a parameter. That is, the parameter value will vary depending on the condition.
Click Save.
Click Release to make the configuration take effect. If you click Cancel, all changes will be discarded.
Click the Parameters tab, on which all parameters are listed.
Click in the upper right corner of the parameter card. You’ll be able to view, modify, and delete parameters, and copy existing parameters as new ones.
On the Conditions tab, you can set different conditions for the parameter. For example, if you set Condition to Audience, the configured parameter value will be updated only for a specific user group.
Integrating SDKsAdd Maven repository configuration to the build.gradle file of your project
Code:
buildscript {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
dependencies {
classpath 'com.android.tools.build:gradle:4.0.1'
classpath 'com.huawei.agconnect:agcp:1.5.2.300'
}
}
allprojects {
repositories {
google()
jcenter()
maven {url 'https://developer.huawei.com/repo/'}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Open the app-level build.gradle file, and configure the Remote Configuration SDK, Analytics SDK, and AppGallery Connect Plugin
Code:
apply plugin: 'com.android.application'
apply plugin: 'com.huawei.agconnect'
android {...}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.huawei.agconnect:agconnect-remoteconfig:1.5.2.300'
}
In AppGallery Connect, click My projects, and find your project from the list. Go to Project settings > General information, download the agconnect-services.json file, and save the file to the app directory of your Android project.
Developing FunctionsIn this step, the Remote Configuration SDK will be used to set in-app default values and fetch parameter values from the cloud.
Add a default value configuration XML file, for example, remote_config.xml, to the res/xml directory of your Android Studio project. In the file, key-value pairs are in testvalue format.
Call applyDefault to pass the default values.
Code:
config.applyDefault(R.xml.remote_config);
You can also create a Map object, and call applyDefault to read and pass the default values.
You can apply parameter values fetched from the cloud either immediately or upon the next launch of your app.
Fetch parameter values and apply them immediatelyThe following code applies parameter values immediately.
Code:
config.fetch().addOnSuccessListener(new OnSuccessListener<ConfigValues>() {
@Override
public void onSuccess(ConfigValues configValues) {
config.apply(configValues);
// Apply parameter values.
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
}
});
In the code, call the fetch API to fetch parameter values from the cloud, and then call the apply API to apply the parameter values in the fetching callback immediately.
Fetch parameter values and apply them upon the next launch of your app.The following code applies parameter values upon the next launch of your app.
Code:
ConfigValues last = config.loadLastFetched();
config.apply(last);
config.fetch().addOnSuccessListener(new OnSuccessListener<ConfigValues>() {
@Override
public void onSuccess(ConfigValues configValues) {
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
}
In the code, call loadLastFetched to obtain the parameter values fetched by calling the fetch API, and call the apply API to apply the parameter values.
Obtain the value for a single parameterYou can call an API to obtain the value for a parameter of a specific type from parameter values fetched from the cloud. The APIs for different parameter types are listed below
Code:
Boolean value = config.getValueAsBoolean("key");
Double value = config.getValueAsDouble("key");
Long value = config.getValueAsLong("key");
String value = config.getValueAsString("key");
byte[] value = config.getValueAsByteArray("key");
Obtain all parameter valuesYou can obtain all in-app default parameter values and on-cloud parameter values by calling getMergedAll.
Code:
Map<String,Object> map = config.getMergedAll();
For details, please refer to the development guide for Remote Configuration.
Will it works on offline?
Thanks for sharing!!!