How many places a normal app can store data - Android Q&A, Help & Troubleshooting

I have an application and I want to swipe all data after uninstalling. I have followed those steps:
1. remove application.
2. remove all app's data in `/sdcard/`. I tracked all this information based on some tracking apps on market such as `SDMaid`
3. remove all cookies.
Here is the code for removing cookies:
Code:
public static void clearCookies(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
Log.e(TAG, "Using clearCookies code for API >=" + String.valueOf(Build.VERSION_CODES.LOLLIPOP_MR1));
CookieManager.getInstance().removeAllCookies(null);
CookieManager.getInstance().flush();
} else {
Log.e(TAG, "Using clearCookies code for API <" + String.valueOf(Build.VERSION_CODES.LOLLIPOP_MR1));
CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(context);
cookieSyncMngr.startSync();
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
cookieManager.removeSessionCookie();
cookieSyncMngr.stopSync();
cookieSyncMngr.sync();
}
}
But when I install again, application still remember who I am. (I don't log in, I just anonymous add some products to cart). I also reset OS and see that everytime I reset, application will load again from fresh state so it means application doesn't store any my private information such as device id ...
My question is: where can an application can store data. I have researched and cannot find more.
thanks

Related

[Q] Why is my onboot broadcastreceiver activty being killed

Im new to android development, so probably be making al the old mistakes.
I created an app it runs fine.
I added an broadcast receiver to do some actions on boot of the device
On boot i want to write some data to the SDcard so ill have to wait for it to become ready.
This is how i tried to do it.
psuedo code/code snipet
Code:
public class bootActivity extends BroadcastReceiver
{
@Override
public void onReceive(final Context context, final Intent intent)
{
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()))
{
new Thread()
{
@Override
public void run()
{
Log.d("TEST","starting");
for(;;)
{
Log.d("TEST","waitloop");
mc=Environment.getExternalStorageState();
try { Thread.sleep(10000); } catch(Exception ex) {}
if(mc.equals(Environment.MEDIA_MOUNTED)) break;
}
Log.d("TEST","do something");
// from here i write to sdcard...
}
}
}
}
In the emulator it works fine, with logcat i see
- D/TEST starting
- D/TEST waitloop (one or more)
- D/TEST do something
and the expected data gets writeen to the SDcard
On my real device i have problems, with logcat is see
- D/TEST starting
- D/TEST waitloop only once
- D/ActivityManager Kill hidden process PID: 333 with NAME test.test.test
Q1) Why is my broadcast activity being killed during boot
(and why does it work in the emulator and not on the real devices)
Q2) If case i'm doing everything wrong
What is the correct/better way to get the same result ?
First you'll want to confirm your process isn't crashing (look for a stack trace in your logcat view in Eclipse or on your phone using the alogcat app).
Besides that, Android is known to kill services if it runs low on memory. This is likely to happen during bootup when a lot of programs are run in sequence. By defining your service a certain way in your androidmanifest you can have the OS re-send intents if the service is killed. There's also a way to make your service a so called foreground service, which Android will think twice about killing. In either case, it's always safe to assume the OS may kill your service at any time so you'll have to pick up where you left off.
Hit up the reference on Services for more info.
- chris
Thanx for the heads up
I checked, my process is not crashing, (no stacktrace or any other errors in logcat)
I wil try to find out what to add to the manifest file
- to have the intents resend
- and how to get a higher dont kill me rank
Thanx
I redid my app doding the SDcard stuf in a service witch is reapplied/restarted if killed and start the service from the bootactivity.
It works fine

Reflection from one app to another app - Access data

I am trying to figure out how to use reflection to access field data from another apk.
Both apks are in debug and signed with the same certificate and they are sharing the same user id. I built out the method to use reflection to retrieve the field value from the other apk.
Code:
public Class<?> getClass(String remoteClass) throws Exception {
Context remoteContext = mContext.createPackageContext(REMOTE_PACKAGE,
Context.CONTEXT_IGNORE_SECURITY | Context.CONTEXT_INCLUDE_CODE);
ClassLoader loader = remoteContext.getClassLoader();
Class<?> cls = loader.loadClass(remoteClass);
return cls;
}
public Object getField(String obfuscatedClass, String obfuscatedField) throws Exception {
try {
Field field = this.dexLoader.getClass(obfuscatedClass).getDeclaredField(obfuscatedField);
field.setAccessible(true);
return field.get(this.reference);
} catch (NullPointerException | IllegalArgumentException | IllegalAccessException | NoSuchFieldException
| SecurityException | ClassNotFoundException e) {
}
return null;
}
Example:
A - APK (A)
In APK (A) I am running the application and while it is running their is real-time data being set...
B - APK (B)
With APK (B) I have the method getClass in which I will use to access the package from APK (A) and then pull the declared field in the package.
The issue is every time I run the apk that uses the reflection on the running application it just returns the default value that the field started with. In java you can use reflection to access a jvm's field values/methods while it is running. I am trying to do the same approach with the android applications but it doesnt look like it is returning real-time data.
Am I doing this all wrong or is this just not possible?
Another thing I am able to do is decompile the running application and make any additions/modifications I want and then recompile. Is there anything I can do to be able to use reflection to retrieve the data from the field values in real-time. Everything is public and static in the apk.
Thank you for your time to whoever is reading this!
Maybe if I were to inject into the other APK reflection methods and then I can use the other apk to invoke the reflection method with reflection to pull data?

Account Kit: Faster app adoption through quick and secure app sign-in using HUAWEI ID

More information like this, you can visit HUAWEI Developer Forum​
Opportunity
The vast number of apps are available for download. There are apps intended for specific purposes and there are similar apps intended for the same purposes. As more apps are available, there is a tendency for users to download more apps to address specific needs or maximize the unique features of similar apps for addressing their needs.
Having an immense number of apps brings stiff competition among developers to ensure that their apps stand out among the other apps. For app users, having a lot of apps in their devices could lead to increased password fatigue and complicated username and password management. It would be a win-win solution for both developers and app end users to have a way that enables app users to sign-in to apps in a fast, simple, and secure manner to have a positive user experience resulting to possible faster app adoption.
What is HUAWEI Account Kit?
HUAWEI Account Kit enables developers to add simple, secure, and quick sign-in and authorization functions to their apps. These functions are achieved by the HUAWEI ID sign-in and authorization solution that complies with OAuth.20 and OpenID Connect. The HUAWEI ID sign-in and authorization solution enables stand-alone apps and apps running on independent developer servers to access user authentication information such as an ID token to enable users to quickly and securely sign-in to apps using their HUAWEI IDs.
How to sign in with HUAWEI ID (ID Token)?
Service process for signing in with HUAWEI ID (ID Token)
The following steps explain the process flow for signing in with HUAWEI ID (ID Token):
1. The app sends a sign-in request to HUAWEI Account SDK upon user sign-in using HUAWEI ID.
2. HUAWEI Account SDK informs the user about the content to be authorized using a user sign-in authorization interface based on the authorization scope in the sign-in request.
3. HUAWEI Account SDK sends an ID token to the app after the user authorizes the app to access the content.
4. The app verifies the ID token.
To request authorization for obtaining an ID token:
1. Present the HUAWEI ID sign-in icon on a sign-in page.
2. Send an authorization request by calling HuaweiIdAuthParamsHelper.setIdToken.
Code:
HuaweiIdAuthParams authParams = new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setIdToken().createParams();
3. Initialize HuaweiIdAuthService using getService method of HuaweiIdAuthManager.
Code:
HuaweiIdAuthService authService = HuaweiIdAuthManager.getService(MainActivity.this, authParams);
4. Bring up the HUAWEI ID sign-in authorization interface using HuaweiIdAuthService.getSignInIntent.
Code:
startActivityForResult(authService.getSignInIntent(), 8888);
5. Obtain HUAWEI ID from the sign-in result by calling HuaweiIdAuthManager.parseAuthResultFromIntent of onActivityResult after completing sign-in authorization.
Code:
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
//Process the sign-in and authorization result and obtain an ID token from AuthHuaweiId.
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 8888) {
Task<AuthHuaweiId> authHuaweiIdTask = HuaweiIdAuthManager.parseAuthResultFromIntent(data);
if (authHuaweiIdTask.isSuccessful()) {
//The sign-in is successful, and the user's HUAWEI ID information and ID token are obtained.
AuthHuaweiId huaweiAccount = authHuaweiIdTask.getResult();
Log.i(TAG, "idToken:" + huaweiAccount.getIdToken());
} else {
//The sign-in failed.
Log.e(TAG, "sign in failed : " +((ApiException)authHuaweiIdTask.getException()).getStatusCode());
}
}
}
To verify ID token validity via local verification
Note: Local verification might fail if the current time of the mobile phone is not in sync with the standard time. Make sure that the current time of the mobile phone to be used for local verification is in sync with the standard time.
1. Obtain a public key from the URI obtained from the jwks_uri field at https://oauth-login.cloud.huawei.com/.well-known/openid-configuration.
Code:
private void getJwks(ICallBack iCallBack) {
OkHttpClient okHttpClient = new OkHttpClient();
final Request request = new Request.Builder()
.url(Constant.CERT_URL)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.i(TAG, "Get ID Token failed.");
iCallBack.onFailed();
}
@Override
public void onResponse(Call call, Response response) {
if (response.isSuccessful()) {
try {
String res = response.body().string();
JSONObject jsonObject = new JSONObject(res);
mJsonArray = jsonObject.getJSONArray("keys");
iCallBack.onSuccess();
} catch (NullPointerException | JSONException | IOException e) {
Log.i(TAG, "parse JsonArray failed." + e.getMessage());
iCallBack.onFailed();
}
}
}
});
}
NOTE: The public key is updated daily and is cached in the app server.
2. Verify the ID token using JWT library such as jwt.io.
Code:
DecodedJWT decoder = JWT.decode(idToken);
Algorithm algorithm = Algorithm.RSA256(mRSAPublicKey , null);
JWTVerifier verifier = JWT.require(algorithm).build();
// verify signature
verifier.verify(decoder);
3. Check if the value of iss is https://accounts.huawei.com.
Code:
decoder.getIssuer().equals(ID_TOKEN_ISSUE);
4. Check if the value of aud is the same as the client_id of the app.
Code:
decoder.getAudience().get(0).equals(CLIENT_ID);
5. Check if the expiration of the ID token is based on the value of exp.
Code:
// Expired, throws TokenExpiredException
verifier.verify(decoder);
If the values of the iss and aud checks out and the expiration of the ID Token is based on the value of exp, the ID token is successfully verified, and the app can use the user information in the sign-in result.
Code:
JSONObject jsonObject = new JSONObject(new String(Base64.decode(decoder.getPayload(), Base64.URL_SAFE), DEFAULT_CHARSET));
For the code, you can refer to IDTokenParser.java in the Client Sample Code.
The Benefits
To the developers
Developers can provide a positive user experience to their app users since the app users do not need to undergo a registration and verification process when signing-in to apps using their HUAWEI ID.
To the end user
End users can sign-in to apps in a fast, simple, and secure manner. Minimizes username and password management since end users can sign-in to different apps integrating the Account Kit just by using their HUAWEI ID.
Learn More
To know more information on how to maximize the features and advantages of HUAWEI Account Kit, go to https://developer.huawei.com/consumer/en/hms/huawei-accountkit
Thank you so much for the post. It is very useful
Is there any image or icons specification like facebook login button has?

Securing Your apps with SafetyDetect

More information like this, you can visit HUAWEI Developer Forum​
What is SafetyDetect?
SafetyDetect is an API or Kits that provide security checks to your application. This will help to protect your app against security threats or malicious programs.
The kits consists of 5 main APIs:
SysIntegrity API: Checks whether the device running your app is secure, for example, whether it is rooted.
AppsCheck API: Obtains a list of malicious apps.
URLCheck API: Determines the threat type of a specific URL.
UserDetect API: Checks whether your app is interacting with a fake user.
WifiDetect API: Checks whether the Wi-Fi to be connected is secure.
Why SafetyDetect?
Why do you want to use safetydetect?
Imagine that if your app deals with sensitive data and/or provide transactional capabilities, you would not want your app security to be compromised.
SafetyDetect will provide the security (device, url, apps, wifi) to your app so that you can ensure that your app and data is not compromised when infected device access your apps.
Using SysIntegrity API
To use SysIntegrity API, there are only a few simple steps.
First, add the required app gallery plugin and safety detect dependency to your build.gradle
Project build.gradle:
Code:
dependencies {
implementation 'com.huawei.hms:safetydetect:{version}'
}
Module build.gradle:
Code:
implementation 'com.huawei.hms:safetydetect:5.0.1.300'
Next, to call the API you will need to generate a nonce value, this value must be at least 16 bytes and is only valid once. This value will be returned also within the SafetyDetect response, so you can use this value to check the validity of the Response.
A nonce can be the app username appended with the timestamp of the request, or any unique value of the application.
Code:
fun invokeSysIntegrityCheck() {
val mClient = SafetyDetect.getClient(this)
val nonce = "This Is Just A Test Nonce".toByteArray(Charsets.UTF_8)
val task = mClient.sysIntegrity(nonce, "your app id")
task.addOnSuccessListener {res ->
// sys integrity call success, result is returned
val result = res.result
}.addOnFailureListener {
// something went wrong, please check your app id and if you have enabled the safety detect api in developer console
it.printStackTrace()
}
}
The result of the check is returned in a json format, sample is below:
Code:
{
"advice":"RESTORE_TO_FACTORY_ROM",
"apkCertificateDigestSha256":[
"yT5JtXRgeIgXssx1gQTsMA9GzM9ER4xAgCsCC69Fz3I="
],
"apkDigestSha256":"6Ihk8Wcv1MLm0O5KUCEVYCI/0KWzAHn9DyN38R3WYu8=",
"apkPackageName":"com.huawei.hms.safetydetectsample",
"basicIntegrity":false,
"nonce":"R2Rra24fVm5xa2Mg",
"timestampMs":1571708929141
}
If the basicIntegrity parameter is false, the user device is at risk. You can choose to notify the user or block the access of the app if you think it’s necessary.
Using AppsCheck API
AppsCheck api is a service where it will detect if any malicious apps are installed on the device. The signature of this malicious apps is stored in the cloud and is periodically updated.
Code:
fun invokeAppsCheck() {
val mClient = SafetyDetect.getClient(this)
val task = mClient.maliciousAppsList
task.addOnSuccessListener {
// service call is successful. we will need to check the app lsit response to see if there is any malicious app installed
val appDataList = it.maliciousAppsList
if (it.rtnCode == CommonCode.OK) {
if (appDataList.isEmpty()){
// malicious apps list is empty, device is safe.
}
else {
// malicious apps is detected on the device
appDataList.forEach {
Log.w("warn", "Malicious app detected: ${it.apkCategory}, ${it.apkPackageName}, ${it.apkSha256}")
}
}
}
}.addOnFailureListener {
// something went wrong
}
}
Using URLCheck API
URLCheck is a service which allows the app to check a particular URL for malicious URL. This is very useful for app that re-directs the user to a lot of other 3rd party URL, such as barcode scanner.
To use URL Check Api:
Code:
fun doUrlCheck(url: String) {
val mClient = SafetyDetect.getClient(this)
// Check the URL
// Param1: URL To be checked
// Param2: your Huawei App ID
// Param3&4: Types of threat to be checked
mClient.urlCheck(url, "your app id here",
UrlCheckThreat.MALWARE,
UrlCheckThreat.PHISHING)
.addOnSuccessListener {
if (it.urlCheckResponse.isEmpty()) {
// No threat or phishing detected
} else {
// Threat detected
}
}
}
So there we have it. Safety Detect is really useful to secure your apps from threats when user is using the app.
For more information, please see the developer link:
https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/introduction-0000001050156325

Writing a Serverless Android app (ft. Huawei's AppGallery Connect)

Part 0 - Why?
Part 1 - Auth
Part 2 - CloudDB
Part 3 - More Cloud
Part 4 - Login and Register
Over the next couple of months I will be releasing a complete end to end guide to creating an Android app using serverless functionality to completely remove the need for any backend server/hosting etc.
These guides will be made up of a weekly live stream which will then be edited into a YouTube video along with each having a blog post for those that prefer a written guide!
But before we get into the actual guide (which will start with 'Part 1' next week) lets start from the... well start! Why might someone want to build a serverless app? what IS a serverless app? and what does Huawei's AppGallery Connect have to do with it?
Well I'm glad you asked!
What is a serverless app?​If Cloud computing takes away the need to manage the hardware, serverless computing takes away the need to manage the software. Its an extension of cloud computing where the provider handles everything about the servers and simply provides some kind of interface for the user to access their services. This might be in the form of an API, SDK, GUI or all of the above!
Why would I want to build a serverless app?​Server management is in its own right a full time job, from setting up the environment to installing and managing the software stack. Security updates, security hardening, authentication (to name a few) are all things that need to be managed in a traditional backend server setup. By using a serverless service all of this management work is removed, you as the app developer simply have access to the resources you need when you need them.
A couple of examples of why or when you might use a serverless system:
Example one - Prototyping​If you need to build an application prototype quickly, you want something that is just going to work and don't want the hassle of setting everything up! By using a serverless system you have instant access to the services you need, this lets you focus on prototyping the app itself.
Example two - Basic requirements​Many apps have very basic backend server requirements. Perhaps they just want to store users details and setting preferences. Or maybe they just need a way to host and download files. These kinds of requirements tend to mean that a full managed backend server is overkill. When your requirements are simple no one wants to spend hours setting it up and managing a server!
Example Three - Small Team/Limited knowledge​If your a small team (or solo) you might simply not have the knowledge or man power to manage servers. The time taken to learn and maintain that knowledge might significantly impact the amount of time you have to develop your application. Sometimes its just much more cost effective to let another company manage this.
What does Huawei's AppGallery Connect have to do with it?​As part of Huawei's AppGallery platform they now offer a wide range of serverless features and functionality. These services come under the AppGallery Connect suite, including but not limited to, database, web hosting, authentication and storage. These services include generous free tiers which make prototyping and developing using these services even more attractive and cost effective.
Because of this we will be using this platform throughout the development guides as we explore what can be done with a serverless Android app!
Part 1 - Auth​
This weeks Video is below
But for those that would rather a written guide, lets get into it!
Project Setup​Starting with a brand new project (or one that has never used Huawei services) we will need to start by setting up a new app. (If you haven't setup your developer account yet sign up!)
If you would like the complete step by step guide on how to get setup check out the Official Documentation, but below is a summery.
Navigate to the the AppGallery Connect area of the developer portal, here you need to create a new project.
{
"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"
}
Follow the new project guide, giving that project a name. Once completed on the left hand menu find the Auth service under the build menu.
Click the enable now button in the top right corner to enable this service for your project. Set a default data processing location, depending on your physical location will most likely help decide which to use. For us we have selected Germany as this is the closest location and within the EU.
From here you are presented with the list of authentication modes, Huawei supports a wide range of services from Facebook login to AppleID. However today we are focusing on the email auth method. Click the enable button next to this.
Now that everything is setup in the project, its time to setup the app! At this point I will assume you have created a new blank project in Android Studio and given it a package name etc.
From the project settings top screen, select the Add app button to setup a new app under this project.
Fill in the add app form, setting the platform, app name, package etc so that it can be added to the created project. Its worth noting at this point, that while we are focusing on Android today many of these services can be used across multiple platforms including iOS and web.
Once completed you will be told to download the agconnect-services.json file and presented with a code to get the core services setup. As we are already focusing on a specific service for today the setup at this point is a little different.
Start by placing your nearly downloaded agconnect-services.json file into the app directory of your project.
Next we will get gradle configured correctly. In your top level gradle build file add the below to your repositories both under buildscript and allprojects
Code:
maven {
url 'https://developer.huawei.com/repo/'
}
And to your dependencies add classpath 'com.huawei.agconnect:agcp:1.4.1.300'
Your file should now look a little like
Code:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
mavenCentral()
maven {
url 'https://developer.huawei.com/repo/'
}
}
dependencies {
classpath "com.android.tools.build:gradle:4.2.2"
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
mavenCentral()
jcenter() // Warning: this repository is going to shut down soon
maven {
url 'https://developer.huawei.com/repo/'
}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Next open your app build.gradle file
Start by adding the agconnect plugin into your plugins list
Code:
plugins {
id 'com.android.application'
id 'com.huawei.agconnect'
}
Make sure to set your midSdkVersion to at least `17` (this is required for any Huawei AppGallery Connect services.
And then in dependencies we are going to add the core and auth services
Code:
implementation 'com.huawei.agconnect:agconnect-core:1.4.1.300'
implementation 'com.huawei.agconnect:agconnect-auth:1.4.1.300'
So your file should now look something like
Code:
plugins {
id 'com.android.application'
id 'com.huawei.agconnect'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "site.zpweb.barker"
minSdkVersion 17
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'com.huawei.agconnect:agconnect-core:1.4.1.300'
implementation 'com.huawei.agconnect:agconnect-auth:1.4.1.300'
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
And thats it! let gradle sync up and we are all good to go!
Registration​As I mentioned before there are a wide range of ways a user can authenticate using the Auth service, but here we are looking at the email service. Email authenticate the user by sending them a code via (your guessed it) Email. The user then inputs this code back into the app to confirm that they are who the say they are, and that they have access to that contact method. We will assume you have setup some kind of register view that will capture a users email.
We start by requesting an authentication code be set to the user, the code to do this looks like
Java:
VerifyCodeSettings settings = VerifyCodeSettings.newBuilder()
.action(VerifyCodeSettings.ACTION_REGISTER_LOGIN)
.sendInterval(30)
.locale(Locale.ENGLISH)
.build();
Task<VerifyCodeResult> task = EmailAuthProvider.requestVerifyCode(emailString, settings);
task.addOnSuccessListener(TaskExecutors.uiThread(), new OnSuccessListener<VerifyCodeResult>() {
@Override
public void onSuccess(VerifyCodeResult verifyCodeResult) {
authCodeDialog();
}
}).addOnFailureListener(TaskExecutors.uiThread(), new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Toast.makeText(RegisterActivity.this,
"Error, code sending failed: " + e,
Toast.LENGTH_LONG).show();
}
});
Lets break this down, we start by defining a `VerifyCodeSettings` object, this holds all the settings relating to the sending of the code. Here we define what locale should be used for the message text that is sent, what kind of code it is and the send interval.
Next we create a task to be run
Java:
Task<VerifyCodeResult> task = EmailAuthProvider.requestVerifyCode(emailString, settings);
Using the EmailAuthProvider, where `emailString` is the email address the user has entered, as a string and the settings object is the VerifyCodeSettings object we just created.
Next we setup an OnSucessListener which will be called if the code was successfully sent to the user. In this example we are calling the method `authCodeDialog();` to display a dialog to enter the code, which will see in a moment.
We also setup an OnFailureListener which simply create a toast on screen to display what ever error is sent back.
Now that we have sent the user a code we should display some view for them to enter that code, in my instance I have the method below, but of course this could be what ever view you wanted.
Java:
private void authCodeDialog() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
final EditText authCodeField = new EditText(this);
alert.setMessage("Enter your auth code below");
alert.setTitle("Authentication Code");
alert.setView(authCodeField);
alert.setPositiveButton("Register", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String authCode = authCodeField.getText().toString();
register(authCode);
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(RegisterActivity.this,
"Registration Cancelled",
Toast.LENGTH_LONG).show();
}
});
alert.show();
}
Finally once the user has inputted the code we can register them as you can see above we have a register method that is called, this has the below code:
Java:
EmailUser emailUser = new EmailUser.Builder()
.setEmail(emailString)
.setVerifyCode(authCode)
.build();
AGConnectAuth.getInstance().createUser(emailUser).addOnSuccessListener(new OnSuccessListener<SignInResult>() {
@Override
public void onSuccess(SignInResult signInResult) {
Toast.makeText(RegisterActivity.this,
"Register Successful: " + signInResult.getUser().getUid(),
Toast.LENGTH_LONG);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Toast.makeText(RegisterActivity.this,
"Registering failed " + e,
Toast.LENGTH_LONG);
}
});
So we start by creating an `EmailUser` using the email address we captured earlier and the authCode that the user has entered. Using that `EmailUser` we then attempt to register. Note that we can also set a password against the `EmailUser`, if we do this when they go to login they do not need to verify their email address again. They can just enter their email and password.
As you can see we pass the created object into the createUser method, attaching OnSuccess and OnFailure Listeners. If the user is successfully registered, i.e the code they entered matches what was sent we are returned a `SignInResult` this object containes the user. So in this example we simply print out the registered users UID to confirm it completed successfully.
Login​
Now that we have covered the sign up process lets look at how we might handle a login process. This would assume that the user has already registered via the above method and is now logging into the app, perhaps after installing it on a new phone.
As I mentioned before if the user signed up without a password then start by sending a verify code, in just the same way as we did during the sign up process. Once we have the code we can generate a `AGCOnnectAuthCredential` object
Java:
AGConnectAuthCredential credential = credential = EmailAuthProvider.credentialWithVerifyCode(
email.getText().toString().trim(),
null,
authCode);
Here we get the email that the user entered (`email` being an `EditText` object). We pass null for the password as we haven't used this, and finally the authCode which the user has entered into the app.
Now we can attempt the sign the user in:
Java:
AGConnectAuth.getInstance().signIn(credential)
.addOnSuccessListener(new OnSuccessListener<SignInResult>() {
@Override
public void onSuccess(SignInResult signInResult) {
Toast.makeText(MainActivity.this, "Sign in successful: " +
signInResult.getUser().getUid(), Toast.LENGTH_LONG);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Toast.makeText(MainActivity.this, "sign in failed:" + e, Toast.LENGTH_LONG);
}
});
We pass the credential object into the signIn method, if the code and email matched and was correct the OnSuccessListener will return the SignInResult object just as it did during the sign up, from here we have access to the users detials.
If for any reason the login fails we will get an Exception in the OnFailureListener.
And thats it! We have setup the application to use Huawei services and configured the app to use email authentication during sign up and log in.
For more information on the Auth service, full documentation can be found here https://developer.huawei.com/consum...Guides/agc-auth-introduction-0000001053732605
We will be back with the next part next week!
Thanks for sharing!!
Except login feature, how will we store huge amount of data?
ask011 said:
Except login feature, how will we store huge amount of data?
Click to expand...
Click to collapse
CloudDB and Cloud Storage are another two services offered which will allow you to store any data you need to! We will be looking at this in the coming weeks so stay tuned!
Part 2 - CloudDB​
This weeks video
Starting with the project as we completed last week (on GitHub) lets now configure the application to support and use the CloudDB functionality from Huawei. Today we will be setting up everything we need to be able to use the CloudDB service and set/get/delete data.
Navigate to the the AppGallery Connect area of the developer portal, select the project we setup last week and on the left hand menu find CloudDB under the build sub menu.
From here enable the service and if you haven't already you will be asked to setup a data location.
Next under the ObjectTypes tab lets create the first data object, click add and you will be presented with a screen like this:
For todays example set your object type name to User, then we will create three fields, id, uid and username as below
Finally create an index called user_id with index field set to id. Leave data permission as they are and save your new data object.
Next go over to the next tab "Cloud DB Zones" and create a new zone, for this example we will call it "Barker".
Head back over to the ObjectTypes tab and press the "Export" button, Pick the JAVA file format, and android for file type. Then enter your Android package name.
This will download two files in a zipped folder, unzip and add these java files to your Android project.
Lets now take a look at these files, if you have followed my naming schemes your User.java should look like:
Java:
/*
* Copyright (c) Huawei Technologies Co., Ltd. 2019-2020. All rights reserved.
* Generated by the CloudDB ObjectType compiler. DO NOT EDIT!
*/
package site.zpweb.barker.model;
import com.huawei.agconnect.cloud.database.CloudDBZoneObject;
import com.huawei.agconnect.cloud.database.Text;
import com.huawei.agconnect.cloud.database.annotations.DefaultValue;
import com.huawei.agconnect.cloud.database.annotations.EntireEncrypted;
import com.huawei.agconnect.cloud.database.annotations.NotNull;
import com.huawei.agconnect.cloud.database.annotations.Indexes;
import com.huawei.agconnect.cloud.database.annotations.PrimaryKeys;
import java.util.Date;
/**
* Definition of ObjectType User.
*
* @since 2021-07-09
*/
@PrimaryKeys({"id"})
@Indexes({"user_id:id"})
public final class User extends CloudDBZoneObject {
private Integer id;
@DefaultValue(stringValue = "0")
private String uid;
@DefaultValue(stringValue = "0")
private String username;
public User() {
super(User.class);
this.uid = "0";
this.username = "0";
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getUid() {
return uid;
}
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
}
Which as you can see is a fairly standard object class with setup for all the fields we defined in the ObjectType.
The other generated file ObjectTypeInfoHelper.java should look like
Java:
/*
* Copyright (c) Huawei Technologies Co., Ltd. 2019-2020. All rights reserved.
* Generated by the CloudDB ObjectType compiler. DO NOT EDIT!
*/
package site.zpweb.barker.model;
import com.huawei.agconnect.cloud.database.CloudDBZoneObject;
import com.huawei.agconnect.cloud.database.ObjectTypeInfo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Definition of ObjectType Helper.
*
* @since 2021-07-09
*/
public final class ObjectTypeInfoHelper {
private static final int FORMAT_VERSION = 2;
private static final int OBJECT_TYPE_VERSION = 10;
public static ObjectTypeInfo getObjectTypeInfo() {
ObjectTypeInfo objectTypeInfo = new ObjectTypeInfo();
objectTypeInfo.setFormatVersion(FORMAT_VERSION);
objectTypeInfo.setObjectTypeVersion(OBJECT_TYPE_VERSION);
List<Class<? extends CloudDBZoneObject>> objectTypeList = new ArrayList<>();
Collections.addAll(objectTypeList, User.class);
objectTypeInfo.setObjectTypes(objectTypeList);
return objectTypeInfo;
}
}
Which is a helper class used by the framework to know what Object classes are available, in this instance just the User class.
You will notice that at this point the code doesn't compile! We need to add in the new CloudDB dependency to the apps build.gradle file
Code:
implementation 'com.huawei.agconnect:agconnect-cloud-database:1.4.8.300'
So your gradle file should now look like:
Code:
plugins {
id 'com.android.application'
id 'com.huawei.agconnect'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "site.zpweb.barker"
minSdkVersion 17
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'com.huawei.agconnect:agconnect-core:1.4.1.300'
implementation 'com.huawei.agconnect:agconnect-auth:1.4.1.300'
implementation 'com.huawei.agconnect:agconnect-cloud-database:1.4.8.300'
implementation 'androidx.appcompat:appcompat:1.3.0'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
Once gradle has synced up we are good to go!
To more easily manage the connection between the CloudDB and functionality within the app I suggest written a separate class to do this. Below is my CloudDBManager class which will act as a wrapper handling much of the CloudDB functionality.
Java:
package site.zpweb.barker.db;
import android.content.Context;
import com.huawei.agconnect.cloud.database.AGConnectCloudDB;
import com.huawei.agconnect.cloud.database.CloudDBZone;
import com.huawei.agconnect.cloud.database.CloudDBZoneConfig;
import com.huawei.agconnect.cloud.database.CloudDBZoneObjectList;
import com.huawei.agconnect.cloud.database.CloudDBZoneQuery;
import com.huawei.agconnect.cloud.database.CloudDBZoneSnapshot;
import com.huawei.agconnect.cloud.database.exceptions.AGConnectCloudDBException;
import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hmf.tasks.Task;
import java.util.ArrayList;
import java.util.List;
import site.zpweb.barker.model.User;
import site.zpweb.barker.utils.Toaster;
public class CloudDBManager {
private int maxUserID = 0;
Toaster toaster = new Toaster();
private final AGConnectCloudDB cloudDB;
private CloudDBZone cloudDBZone;
public CloudDBManager(){
cloudDB = AGConnectCloudDB.getInstance();
}
public static void initCloudDB(Context context){
AGConnectCloudDB.initialize(context);
}
public void openCloudDBZone(Context context){
CloudDBZoneConfig config = new CloudDBZoneConfig("Barker",
CloudDBZoneConfig.CloudDBZoneSyncProperty.CLOUDDBZONE_CLOUD_CACHE,
CloudDBZoneConfig.CloudDBZoneAccessProperty.CLOUDDBZONE_PUBLIC);
config.setPersistenceEnabled(true);
try {
cloudDBZone = cloudDB.openCloudDBZone(config, true);
} catch (AGConnectCloudDBException e) {
toaster.sendErrorToast(context, e.getLocalizedMessage());
}
}
public void closeCloudDBZone(Context context){
try {
cloudDB.closeCloudDBZone(cloudDBZone);
} catch (AGConnectCloudDBException e) {
toaster.sendErrorToast(context, e.getLocalizedMessage());
}
}
public void upsertUser(User user, Context context) {
Task<Integer> upsertTask = cloudDBZone.executeUpsert(user);
executeTask(upsertTask, context);
}
public void upsertUsers(List<User> users,Context context) {
Task<Integer> upsertTask = cloudDBZone.executeUpsert(users);
executeTask(upsertTask, context);
}
private void executeTask(Task<Integer> task,Context context) {
task.addOnSuccessListener(integer -> toaster.sendSuccessToast(context, "upsert successful"))
.addOnFailureListener(e -> toaster.sendErrorToast(context, e.getLocalizedMessage()));
}
public void deleteUser(User user){
cloudDBZone.executeDelete(user);
}
public int getMaxUserID(){
return maxUserID;
}
private void updateMaxUserID(User user){
if (maxUserID < user.getId()) {
maxUserID = user.getId();
}
}
public void getAllUsers(Context context){
queryUsers(CloudDBZoneQuery.where(User.class), context);
}
public void queryUsers(CloudDBZoneQuery<User> query, Context context) {
Task<CloudDBZoneSnapshot<User>> task = cloudDBZone.executeQuery(query,
CloudDBZoneQuery.CloudDBZoneQueryPolicy.POLICY_QUERY_FROM_CLOUD_ONLY);
task.addOnSuccessListener(userCloudDBZoneSnapshot -> processResults(userCloudDBZoneSnapshot, context))
.addOnFailureListener(e -> toaster.sendErrorToast(context, e.getLocalizedMessage()));
}
private void processResults(CloudDBZoneSnapshot<User> userCloudDBZoneSnapshot, Context context) {
CloudDBZoneObjectList<User> userCursor = userCloudDBZoneSnapshot.getSnapshotObjects();
List<User> userList = new ArrayList<>();
try {
while (userCursor.hasNext()) {
User user = userCursor.next();
updateMaxUserID(user);
userList.add(user);
}
//HAVE USER LIST
} catch (AGConnectCloudDBException e) {
toaster.sendErrorToast(context, e.getLocalizedMessage());
} finally {
userCloudDBZoneSnapshot.release();
}
}
}
Lets break it down and take a look at what we are going to be able to do with this class.
First we define the variables we are going to need, the most important thing here is maxUserID. CloudDB currently doesn't have any auto increment support so we will need to keep a running check on what is the last used ID.
Next we have the class constructor where we will get an instance of the CloudDB interface to be used by the other methods in this class.
Java:
public CloudDBManager(){
cloudDB = AGConnectCloudDB.getInstance();
}
Next up with a static init method, the CloudDB initialize method must be called at the start of your application, so this static method is used to do just that!
Java:
public static void initCloudDB(Context context){
AGConnectCloudDB.initialize(context);
}
In the openCloudDBZone method we setup the configured cloud zone, this is where the data will be saved to and received from. Note that you could have multiple zone's that all use the same ObjectType's. They wouldn't however have access to other zone's data. Useful if you have multiple applications that require similar data structures.
Java:
public void openCloudDBZone(Context context){
config = new CloudDBZoneConfig("Barker",
CloudDBZoneConfig.CloudDBZoneSyncProperty.CLOUDDBZONE_CLOUD_CACHE,
CloudDBZoneConfig.CloudDBZoneAccessProperty.CLOUDDBZONE_PUBLIC);
config.setPersistenceEnabled(true);
try {
cloudDBZone = cloudDB.openCloudDBZone(config, true);
} catch (AGConnectCloudDBException e) {
toaster.sendErrorToast(context, e.getLocalizedMessage());
}
}
As we have an open method we should also have a close method to shut down the apps access to that zone.
Java:
public void closeCloudDBZone(Context context){
try {
cloudDB.closeCloudDBZone(cloudDBZone);
} catch (AGConnectCloudDBException e) {
toaster.sendErrorToast(context, e.getLocalizedMessage());
}
}
Next we have three methods that handle the upsert of User's, that is either the update or insert depending on if the user already exists in the database. The executeTask method sets the success/failure listeners while the other two methods simply set up the task depending on if we are upserting one user or a list of users.
Java:
public void upsertUser(User user, Context context) {
Task<Integer> upsertTask = cloudDBZone.executeUpsert(user);
executeTask(upsertTask, context);
}
public void upsertUsers(List<User> users,Context context) {
Task<Integer> upsertTask = cloudDBZone.executeUpsert(users);
executeTask(upsertTask, context);
}
private void executeTask(Task<Integer> task,Context context) {
task.addOnSuccessListener(integer -> toaster.sendSuccessToast(context, "upsert successful"))
.addOnFailureListener(e -> toaster.sendErrorToast(context, e.getLocalizedMessage()));
}
Next we have a simple method that will delete a User from the database
Java:
public void deleteUser(User user){
cloudDBZone.executeDelete(user);
}
Then a getter for the maxUserID, and a method to update the maxUserID. If the given User has a greater ID than the current max, update the max ID to that Users ID.
Java:
public int getMaxUserID(){
return maxUserID;
}
private void updateMaxUserID(User user){
if (maxUserID < user.getId()) {
maxUserID = user.getId();
}
}
And finally we have three methods that handle the querying of data, the getAllUsers method makes use of a predefined query which simply asks for all objects that are of the type User.
Java:
public void getAllUsers(Context context){
queryUsers(CloudDBZoneQuery.where(User.class), context);
}
Next the queryUsers method which will generate the query task and runs it, on success we then pass the result into processResult.
Java:
public void queryUsers(CloudDBZoneQuery<User> query, Context context) {
Task<CloudDBZoneSnapshot<User>> task = cloudDBZone.executeQuery(query,
CloudDBZoneQuery.CloudDBZoneQueryPolicy.POLICY_QUERY_FROM_CLOUD_ONLY);
task.addOnSuccessListener(userCloudDBZoneSnapshot -> processResults(userCloudDBZoneSnapshot, context))
.addOnFailureListener(e -> toaster.sendErrorToast(context, e.getLocalizedMessage()));
}
Note that for the query variable we can create the type of query we need. We will look at examples of this next week (other than just the provided CloudDBZoneQuery.where(User.class)
The final method in this manager is the processResult, here we use a cursor to move over the result returned from the query. For each object in the result we update the max UserID and then add that User to a list. This is the point where we would then do something with that list, perhaps update the UI to show the result or do some other processing.
Java:
private void processResults(CloudDBZoneSnapshot<User> userCloudDBZoneSnapshot, Context context) {
CloudDBZoneObjectList<User> userCursor = userCloudDBZoneSnapshot.getSnapshotObjects();
List<User> userList = new ArrayList<>();
try {
while (userCursor.hasNext()) {
User user = userCursor.next();
updateMaxUserID(user);
userList.add(user);
}
//HAVE USER LIST
} catch (AGConnectCloudDBException e) {
toaster.sendErrorToast(context, e.getLocalizedMessage());
} finally {
userCloudDBZoneSnapshot.release();
}
}
We now have all the basic methods we might need to get/set/delete the User object.
We have just a little more setup to do and then we are ready to start using the CloudDB!
As I mentioned earlier we need to init the CloudDB before we can use it anywhere in the app. The best way to do this will be to make it part of the Application class's onCreate method. For example:
Java:
package site.zpweb.barker;
import android.app.Application;
import site.zpweb.barker.db.CloudDBManager;
public class BarkerApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
CloudDBManager.initCloudDB(this);
}
}
Setting this as the application class in your manifest:
XML:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="site.zpweb.barker">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Barker"
android:name=".BarkerApplication">
<activity android:name=".RegisterActivity"></activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
And that's it! We are now good to go, next week we will look at how we might actually make use of this functionality as well as expand on ObjectType's and storing more complex data in the cloud!
Can we store custom object cloud db?
Part 3 - More CloudDB​
Last time we looked at the basic setup of the CloudDB service, how to get things configured and how you can get started with the service. Now this is in place lets take a look at the service in more detail. We started working on a CloudDBManager that was going to handle all the communication between the CloudDB service and the rest of the app. This was a great start but before we dig any deep lets look at a few improvements to this.
Listen for Database Changes​
In the current CloudDBManager if we want to check for any changes to the database we had to manually call getAllUsers(). This is fine if we aren't really interested in when changes are made to the database, however if we do want to keep an up to date local copy of the data (for example posts in a feed) we need to look at adding a Snapshot Listener. This will tell the CloudDB service to execute a given query and process the results in real time.
Lets start by defining a new OnSnapShotListener for the Class User when the listener is given a snapshot we pass this into the processResults method we created last week.
Java:
private final OnSnapshotListener<User> snapshotListener = (cloudDBZoneSnapshot, e) -> processResults(cloudDBZoneSnapshot);
Next we create a method that will subscribe that Snapshot Listener to the CloudDBZone with an applied query, in this instance just the simple query to return all Users
Java:
public void addSubscription() {
CloudDBZoneQuery < User > snapshotQuery = CloudDBZoneQuery.where(User.class).equalTo("uid", "");
try {
ListenerHandler handler = cloudDBZone.subscribeSnapshot(snapshotQuery,
CloudDBZoneQuery.CloudDBZoneQueryPolicy.POLICY_QUERY_FROM_CLOUD_ONLY,
snapshotListener);
} catch (Exception e) {
toaster.sendErrorToast(context, e.getLocalizedMessage());
}
}
With this in place we can now tweak the openCloudDBZone method, by using a task based approach we are able to add an onSuccessListener. So long as the zone is successfully opened we can called the addSubscription() method and start listening for new data.
Java:
public void openCloudDBZoneV2() {
CloudDBZoneConfig config = new CloudDBZoneConfig("Barker",
CloudDBZoneConfig.CloudDBZoneSyncProperty.CLOUDDBZONE_CLOUD_CACHE,
CloudDBZoneConfig.CloudDBZoneAccessProperty.CLOUDDBZONE_PUBLIC);
config.setPersistenceEnabled(true);
Task < CloudDBZone > task = cloudDB.openCloudDBZone2(config, true);
task.addOnSuccessListener(zone - > {
cloudDBZone = zone;
addSubscription();
}).addOnFailureListener(e - > toaster.sendErrorToast(context, e.getLocalizedMessage()));
}
Use userList​In the processResults method from last week we took the data snapshot and converted it into a list of User objects. We didn't then do anything with this nor did we have a method to pass that data onto somewhere else in the app. Lets change that!
We will start by creating a new public interface called UserCallBack this will be implemented by any class that wants to use an instance of the CloudDBManager. Currently the interface is pretty simple with just three methods:
Java:
public interface UserCallBack {
void onAddOrQuery(List < User > userList);
void onDelete(List < User > userList);
void onError(String errorMessage);
}
We create a variable for this Call back within the CloudDBManager like:
Java:
private final UserCallBack callBack;
And finally as part of the CloudDBManager init method we require an instance of the UserCallBack
Java:
public CloudDBManager(Context context, UserCallBack callBack) {
cloudDB = AGConnectCloudDB.getInstance();
this.context = context;
this.callBack = callBack;
}
Now when we have processed the result of a query we can pass that data back to the calling class using the callback. For example the processResult method now looks like:
Java:
private void processResults(CloudDBZoneSnapshot < User > userCloudDBZoneSnapshot) {
CloudDBZoneObjectList < User > userCursor = userCloudDBZoneSnapshot.getSnapshotObjects();
List < User > userList = new ArrayList < > ();
try {
while (userCursor.hasNext()) {
User user = userCursor.next();
updateMaxUserID(user);
userList.add(user);
}
callBack.onAddOrQuery(userList);
} catch (AGConnectCloudDBException e) {
callBack.onError(e.getLocalizedMessage());
toaster.sendErrorToast(context, e.getLocalizedMessage());
} finally {
userCloudDBZoneSnapshot.release();
}
}
We now have a way to both pass back the user list and also any error message that might be given during the processing!
The final CloudDBManager should look something like:
A manager class for the AGC CloudDB service
A manager class for the AGC CloudDB service. GitHub Gist: instantly share code, notes, and snippets.
gist.github.com
Authentication Manager​With the changes made above lets take a look at how we can use this to gain access to the database data. Specifically within the `AuthenticationManager`.
First we must now implement the new interface like so:
Java:
public class AuthenticationManager implements CloudDBManager.UserCallBack{
...
@Override
public void onAddOrQuery(List<User> userList) {
}
@Override
public void onDelete(List<User> userList) {
}
@Override
public void onError(String errorMessage) {
}
...
}
The onAddOrQuery method will be given the userList returned when a snapshot is processed, we can implement code here to update the UI or confirm if a user is already registered for example.
In this Classes init method we will also need to pass itself in as the UserCallBack. The setup of the CloudDBManager object will now look like:
Java:
dbManager = new CloudDBManager(context, this);
dbManager.createObjectType();
dbManager.openCloudDBZoneV2();
We are now in a good position to query data, view it and upsert it! Join us next week when we start configuring the other Objects we are going to be using, expand the User object and make the CloudDBManager generic for any CloudDB Object!
devwithzachary said:
Part 0 - Why?
Part 1 - Auth
Part 2 - CloudDB
Over the next couple of months I will be releasing a complete end to end guide to creating an Android app using serverless functionality to completely remove the need for any backend server/hosting etc.
These guides will be made up of a weekly live stream which will then be edited into a YouTube video along with each having a blog post for those that prefer a written guide!
But before we get into the actual guide (which will start with 'Part 1' next week) lets start from the... well start! Why might someone want to build a serverless app? what IS a serverless app? and what does Huawei's AppGallery Connect have to do with it?
Well I'm glad you asked!
What is a serverless app?​If Cloud computing takes away the need to manage the hardware, serverless computing takes away the need to manage the software. Its an extension of cloud computing where the provider handles everything about the servers and simply provides some kind of interface for the user to access their services. This might be in the form of an API, SDK, GUI or all of the above!
Why would I want to build a serverless app?​Server management is in its own right a full time job, from setting up the environment to installing and managing the software stack. Security updates, security hardening, authentication (to name a few) are all things that need to be managed in a traditional backend server setup. By using a serverless service all of this management work is removed, you as the app developer simply have access to the resources you need when you need them.
A couple of examples of why or when you might use a serverless system:
Example one - Prototyping​If you need to build an application prototype quickly, you want something that is just going to work and don't want the hassle of setting everything up! By using a serverless system you have instant access to the services you need, this lets you focus on prototyping the app itself.
devwithzachary said:
Part 0 - Why?
Part 1 - Auth
Part 2 - CloudDB
Over the next couple of months I will be releasing a complete end to end guide to creating an Android app using serverless functionality to completely remove the need for any backend server/hosting etc.
These guides will be made up of a weekly live stream which will then be edited into a YouTube video along with each having a blog post for those that prefer a written guide!
But before we get into the actual guide (which will start with 'Part 1' next week) lets start from the... well start! Why might someone want to build a serverless app? what IS a serverless app? and what does Huawei's AppGallery Connect have to do with it?
Well I'm glad you asked!
What is a serverless app?​If Cloud computing takes away the need to manage the hardware, serverless computing takes away the need to manage the software. Its an extension of cloud computing where the provider handles everything about the servers and simply provides some kind of interface for the user to access their services. This might be in the form of an API, SDK, GUI or all of the above!
Why would I want to build a serverless app?​Server management is in its own right a full time job, from setting up the environment to installing and managing the software stack. Security updates, security hardening, authentication (to name a few) are all things that need to be managed in a traditional backend server setup. By using a serverless service all of this management work is removed, you as the app developer simply have access to the resources you need when you need them.
A couple of examples of why or when you might use a serverless system:
Example one - Prototyping​If you need to build an application prototype quickly, you want something that is just going to work and don't want the hassle of setting everything up! By using a serverless system you have instant access to the services you need, this lets you focus on prototyping the app itself.
Example two - Basic requirements​Many apps have very basic backend server requirements. Perhaps they just want to store users details and setting preferences. Or maybe they just need a way to host and download files. These kinds of requirements tend to mean that a full managed backend server is overkill. When your requirements are simple no one wants to spend hours setting it up and managing a server!
Example Three - Small Team/Limited knowledge​If your a small team (or solo) you might simply not have the knowledge or man power to manage servers. The time taken to learn and maintain that knowledge might significantly impact the amount of time you have to develop your application. Sometimes its just much more cost effective to let another company manage this.
What does Huawei's AppGallery Connect have to do with it?​As part of Huawei's AppGallery platform they now offer a wide range of serverless features and functionality. These services come under the AppGallery Connect suite, including but not limited to, database, web hosting, authentication and storage. These services include generous free tiers which make prototyping and developing using these services even more attractive and cost effective.
Because of this we will be using this platform throughout the development guides as we explore what can be done with a serverless Android app!
Click to expand...
Click to collapse
Example two - Basic requirements​Many apps have very basic backend server requirements. Perhaps they just want to store users details and setting preferences. Or maybe they just need a way to host and download files. These kinds of requirements tend to mean that a full managed backend server is overkill. When your requirements are simple no one wants to spend hours setting it up and managing a server!
Example Three - Small Team/Limited knowledge​If your a small team (or solo) you might simply not have the knowledge or man power to manage servers. The time taken to learn and maintain that knowledge might significantly impact the amount of time you have to develop your application. Sometimes its just much more cost effective to let another company manage this.
What does Huawei's AppGallery Connect have to do with it?​As part of Huawei's AppGallery platform they now offer a wide range of serverless features and functionality. These services come under the AppGallery Connect suite, including but not limited to, database, web hosting, authentication and storage. These services include generous free tiers which make prototyping and developing using these services even more attractive and cost effective.
Because of this we will be using this platform throughout the development guides as we explore what can be done with a serverless Android app!
Click to expand...
Click to collapse
Useful sharing, thanks
Part 4 - Login and Register​Today we are going to look at getting the Login and Register process fully complete. This will include some refactoring to the code we have worked on before.
Authentication Manager​
With a CloudDBManager now in place that is able to handle the User object we created its time we make changes to the AuthenticationManager so that this CloudDBManager is correctly used to retrieve user data at login/register.
Firstly we have a number of variables that we might be passing into the AuthenticationManager. Up until this point we where only passing in a phone number or an email address and this was handled by the contactString variable. However now that we will be accepting registration information, more data needs to be accept.
When logging in the use may be using their mobile phone number or their email address. When registering they might provide either the phone number or email address or both, and in addition a username and display name.
With these elements in mind lets create a simple data object to store this and pass it into the AuthenticationManager as needed. This will look like below, with standard Getters/Setters and constructor.
Java:
public class LoginRegisterData {
String phoneNumber,email,username,displayName;
public LoginRegisterData(String phoneNumber, String email, String username, String displayName) {
this.phoneNumber = phoneNumber;
this.email = email;
this.username = username;
this.displayName = displayName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
}
We will pass this data into the AuthenticationManager constructor like so:
Java:
public class AuthenticationManager implements CloudDBManager.UserCallBack{
Toaster toaster = new Toaster();
Context context;
int authType;
LoginRegisterData loginRegisterData;
boolean isLogin;
private final CloudDBManager dbManager;
private String loginUserUID = "0";
public AuthenticationManager(Context context, int authType, LoginRegisterData loginRegisterData, boolean isLogin){
this.context = context;
this.authType = authType;
this.loginRegisterData = loginRegisterData;
this.isLogin = isLogin;
dbManager = new CloudDBManager(context, this);
dbManager.createObjectType();
dbManager.openCloudDBZoneV2();
}
...
}
You will also notice that we have removed the contactString from the construct. As this variable has been removed we should also make sure to remove its usage and replace with the correct data from the LoginRegisterData object.
In places where we where expecting this string to contain the email address we should now use loginRegisterData.getEmail() and in places where we where expecting the phone number we should use loginRegisterData.getPhoneNumber().
Next lets take a look at the getUser() method. Up until now we have simply gotten the AGConnectUser for the currently authenticated user, however we haven't actually then done anything with that. Now we should use that authenticated user to get the stored User object from the database.
Java:
private void getUser(){
AGConnectUser user = AGConnectAuth.getInstance().getCurrentUser();
loginUserUID = user.getUid();
CloudDBZoneQuery<User> snapshotQuery = CloudDBZoneQuery.where(User.class).equalTo("uid", loginUserUID);
dbManager.queryUsers(snapshotQuery);
}
...
@Override
public void onQuery(List<User> userList) {
if (userList.size() == 1) {
User user = userList.get(0);
if (user.getUid().equals(loginUserUID)){
saveLoginDetail(user);
proceedToFeed();
}
}
}
Here we are getting the UID of the authenticated user and then querying the database for the user with that UID.
In the onQuery callback we can check that only one user was returned, and then triple check that the returned user does match the UID. From here we call two new methods saveLoginDetail() and proceedToFeed().
saveLoginDetail( ) is used to save a local copy of the logged in users ID and set a flag to say that we are now logged in. This way the next time the user opens the application we can check this flag and the user will not have to login every time they open the app.
Java:
private void saveLoginDetail(User user) {
SharedPreferences preferences = context.getSharedPreferences("loginDetail", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("isLoginedIn", true);
editor.putInt("userId", user.getId());
}
The proceedToFeed() method will simply start the FeedActivity now that we are logged in.
Java:
private void proceedToFeed(){
context.startActivity(new Intent(context, FeedActivity.class));
}
From the Registration side of the process the only thing to change is the addition of being able to set the username and display name as below.
Java:
private void saveRegisteredUser(SignInResult signInResult){
User user = new User();
user.setId(dbManager.getMaxUserID() + 1);
user.setUid(signInResult.getUser().getUid());
user.setUsername(loginRegisterData.getUsername());
user.setDisplayname(loginRegisterData.getDisplayName());
dbManager.upsertUser(user);
}
In the onUpsert call back we use the same two methods saveLoginDetail() and proceedtoFeed() as the login process.
Java:
@Override
public void onUpsert(User user){
saveLoginDetail(user);
proceedToFeed();
}
And that's it! Your AuthenticationManager should now look like this: https://gist.github.com/devwithzachary/97e23d7c813fd917a13ab88de34f9751
Of course as we have now changed the constructor there are some changes that need to be made in both the login and register activities.
Login Activity​Within the MainActivity which is the login activity for us, lets start by creating a simple method to generate the LoginRegisterData object
Java:
private LoginRegisterData getLoginRegisterData() {
String emailString = email.getText().toString().trim();
String phoneString = phone.getText().toString().trim();
return new LoginRegisterData(phoneString, emailString, "", "");
}
As you can see we take the email and phone number input and build the object. At this point if we used this method in the phoneLogin and emailLogin onClick listeners we can see there is code duplication. So instead lets extract a method to trigger the login process.
Java:
private void login(int authType) {
authManager = new AuthenticationManager(MainActivity.this,
authType,
getLoginRegisterData(),
true);
authManager.sendVerifyCode();
}
As you can see we generate the AuthenticateManager passing in the LoginRegisterData and the authType. The OnClick Listeners for each button are now just one line calling this method and passing in the AuthType as needed. The MainActivity should now look like this: https://gist.github.com/devwithzachary/b9cb25f1b86b0503a5f4883345201b9d
Register Activity​For the register activity we do the same process, however we will also add two new EditText fields so that we can accept the user input for username and displayname. Otherwise the process is the same. Create the LoginRegisterData and pass that into the AuthenticationManager. This this in mind the Register activity will look something like: https://gist.github.com/devwithzachary/10a3837b0e9abbc32e1b3dcf083f4276
And that's it! we are now in a good state with the login and register flow which will result in a user being authenticated, logged in and use saving the ID of that user along with setting a flag to confirm the user is logged in.

Categories

Resources