Xamarin Android Climate App highlights Climate Consciousness API and Login with Huawei Id : HMSCore

Overview

On this article, I’ll create a demo app together with the mixing of HMS Account & Consciousness Equipment which relies on Cross platform Know-how Xamarin. Consumer can simply login with Huawei Id and get the small print of their metropolis climate info. I’ve carried out Huawei Id for login and Climate Consciousness for climate forecasting.

Account Equipment Service Introduction

HMS Account Equipment means that you can connect with the Huawei ecosystem utilizing your HUAWEI ID from a variety of gadgets, reminiscent of cellphones, tablets, and good screens.

It’s a easy, safe, and fast sign-in and authorization capabilities. As an alternative of getting into accounts and passwords and ready for authentication.

Complies with worldwide requirements and protocols reminiscent of OAuth2.0 and OpenID Join, and helps two-factor authentication (password authentication and cell quantity authentication) to make sure excessive safety.

Climate Consciousness Service Introduction

HMS Climate Consciousness Equipment permits your app with the power to acquire contextual info together with customers’ present time, location, habits, audio machine standing, ambient gentle, climate, and close by beacons. Your app can acquire perception right into a person’s present state of affairs extra effectively, making it doable to ship a wiser, extra thoughtful person expertise.

Prerequisite

1. Xamarin Framework

2. Huawei telephone

3. Visible Studio 2019

App Gallery Integration course of

1. Signal In and Create or Select a undertaking on AppGallery Join portal.

r/HMSCore - Expert: Xamarin Android Weather App highlights Weather Awareness API and Login with Huawei Id

2. Add SHA-256 key.

r/HMSCore - Expert: Xamarin Android Weather App highlights Weather Awareness API and Login with Huawei Id

3. Navigate to Mission settings and obtain the configuration file.

r/HMSCore - Expert: Xamarin Android Weather App highlights Weather Awareness API and Login with Huawei Id

4. Navigate to Basic Data, after which present Information Storage location.

r/HMSCore - Expert: Xamarin Android Weather App highlights Weather Awareness API and Login with Huawei Id

5. Navigate to Handle APIs and allow APIs which require by software.

r/HMSCore - Expert: Xamarin Android Weather App highlights Weather Awareness API and Login with Huawei Id

Xamarin Account Equipment Setup Course of

1. Obtain Xamarin Plugin all of the aar and zip recordsdata from under url:

https://developer.huawei.com/client/en/doc/growth/HMS-Plugin-Library-V1/xamarin-sdk-download-0000001050768441-V1

r/HMSCore - Expert: Xamarin Android Weather App highlights Weather Awareness API and Login with Huawei Id

2. Open the XHwid-5.03.302.sln resolution in Visible Studio.

r/HMSCore - Expert: Xamarin Android Weather App highlights Weather Awareness API and Login with Huawei Id

Xamarin Climate Consciousness Equipment Setup Course of

  1. Obtain Xamarin Plugin all of the aar and zip recordsdata from under url:

https://developer.huawei.com/client/en/doc/growth/HMS-Plugin-Library-V1/xamarin-0000001061535799-V1

r/HMSCore - Expert: Xamarin Android Weather App highlights Weather Awareness API and Login with Huawei Id

2. Open the XAwarness-1.0.7.303.sln resolution in Visible Studio.

r/HMSCore - Expert: Xamarin Android Weather App highlights Weather Awareness API and Login with Huawei Id

3. Navigate to Resolution Discover and proper click on on jar Add > Exsiting Merchandise and select aar file which obtain in Step 1.

r/HMSCore - Expert: Xamarin Android Weather App highlights Weather Awareness API and Login with Huawei Id

4. Proper click on on added aar file, then select Properties > Construct Motion > LibraryProjectZip

Word: Repeat Step 3 & Four for all aar file.

5. Construct the Library and make dll recordsdata.

Xamarin App Improvement

1. Open Visible Studio 2019 and Create A New Mission.

2. Navigate to Resolution Discover > Mission > Property > Add Json file.

3. Navigate to Resolution Discover > Mission > Add > Add New Folder.

4. Navigate to Folder(created) > Add > Add Current and add all dll recordsdata.

r/HMSCore - Expert: Xamarin Android Weather App highlights Weather Awareness API and Login with Huawei Id

5. Proper-click on Properties, select Construct Motion > None

r/HMSCore - Expert: Xamarin Android Weather App highlights Weather Awareness API and Login with Huawei Id

6. Navigate to Resolution Discover > Mission > Reference > Proper Click on > Add References, then navigate to Browse and add all dll recordsdata from just lately added folder.

r/HMSCore - Expert: Xamarin Android Weather App highlights Weather Awareness API and Login with Huawei Id

7. Added reference, then click on OK.

r/HMSCore - Expert: Xamarin Android Weather App highlights Weather Awareness API and Login with Huawei Id

Account Equipment Integration

Improvement Process

1. Name the HuaweiIdAuthParamsHelper.SetAuthorizationCode technique to ship an authorization request.

HuaweiIdAutParams mAuthParam;
mAuthParam = new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DefaultAuthRequestParam)
                     .SetProfile()
                     .SetAuthorizationCode()
                     .CreateParams();

2. Name the GetService technique of HuaweiIdAuthManager to initialize the IHuaweiIdAuthService object.

IHuaweiIdAuthService mAuthManager;
mAuthManager = HuaweiIdAuthManager.GetService(this, mAuthParam);

3. Name the IHuaweiIdAuthService.SignInIntent technique to deliver up the HUAWEI ID authorization & sign-in display.

StartActivityForResult(mAuthManager.SignInIntent, 8888);

4. Course of the consequence after the authorization & sign-in is full.

protected override void OnActivityResult(int requestCode, Outcome resultCode, Intent knowledge)
        {
            base.OnActivityResult(requestCode, resultCode, knowledge);
            if (requestCode == 8888)
            {
                //login success
                Job authHuaweiIdTask = HuaweiIdAuthManager.ParseAuthResultFromIntent(knowledge);
                if (authHuaweiIdTask.IsSuccessful)
                {
                    AuthHuaweiId huaweiAccount = (AuthHuaweiId)authHuaweiIdTask.TaskResult();
                    Log.Information(TAG, "signIn get code success.");
                    Log.Information(TAG, "ServerAuthCode: " + huaweiAccount.AuthorizationCode);
                }
                else
                {
                  Log.Information(TAG, "signIn failed: " +((ApiException)authHuaweiIdTask.Exception).StatusCode);
                 }
            }
         }

LoginActivity.cs

This exercise carry out all of the operation relating to login with Huawei Id.

utilizing Android.App;
utilizing Android.Content material;
utilizing Android.Content material.PM;
utilizing Android.OS;
utilizing Android.Runtime;
utilizing Android.Assist.V4.App;
utilizing Android.Assist.V4.Content material;
utilizing Android.Assist.V7.App;
utilizing Android.Util;
utilizing Android.Views;
utilizing Android.Widget;
utilizing Com.Huawei.Agconnect.Config;
utilizing Com.Huawei.Hmf.Duties;
utilizing Com.Huawei.Hms.Widespread;
utilizing Com.Huawei.Hms.Assist.Hwid;
utilizing Com.Huawei.Hms.Assist.Hwid.Request;
utilizing Com.Huawei.Hms.Assist.Hwid.Outcome;
utilizing Com.Huawei.Hms.Assist.Hwid.Service;
utilizing System;
utilizing System.Collections.Generic;
utilizing System.Linq;
utilizing System.Textual content;

namespace WeatherAppDemo
{
    [Activity(Label = "LoginActivity", Theme = "@style/AppTheme", MainLauncher = true)]
    public class LoginActivity : AppCompatActivity
    {
        personal static String TAG = "LoginActivity";
        personal HuaweiIdAuthParams mAuthParam;
        public static IHuaweiIdAuthService mAuthManager;

        personal Button btnLoginWithHuaweiId;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Necessities.Platform.Init(this, savedInstanceState);
            SetContentView(Useful resource.Structure.login_activity);


            btnLoginWithHuaweiId = FindViewById

Climate Consciousness API Integration

Assigning Permissions within the Manifest File

Earlier than calling the climate consciousness functionality, assign required permissions within the manifest file.



Creating Capabilities

Name the climate functionality API by way of the Seize Shopper object.

personal async void GetWeatherStatus()
{
    var weatherTask = Consciousness.GetCaptureClient(this).GetWeatherByDeviceAsync();
    await weatherTask;
    if (weatherTask.IsCompleted && weatherTask.Outcome != null)
    {
        IWeatherStatus weatherStatus = weatherTask.Outcome.WeatherStatus;
        WeatherSituation weatherSituation = weatherStatus.WeatherSituation;
        Scenario state of affairs = weatherSituation.Scenario;
        string consequence = $"Metropolis:{weatherSituation.Metropolis.Identify}n";
        consequence += $"Climate id is {state of affairs.WeatherId}n";
        consequence += $"CN Climate id is {state of affairs.CnWeatherId}n";
        consequence += $"Temperature is {state of affairs.TemperatureC}Celcius";
        consequence += $",{state of affairs.TemperatureF}Farenheitn";
        consequence += $"Wind pace is {state of affairs.WindSpeed}km/hn";
        consequence += $"Wind path is {state of affairs.WindDir}n";
        consequence += $"Humidity is {state of affairs.Humidity}%";
    }
    else
    {
        var exception = weatherTask.Exception;
        string errorMessage = $"{AwarenessStatusCodes.GetMessage(exception.GetStatusCode())}: {exception.Message}";
    }
}

MainActivity.cs

This exercise carry out all of the operation relating to Climate Consciousness api like present metropolis climate and different info.

utilizing System;
utilizing Android;
utilizing Android.App;
utilizing Android.OS;
utilizing Android.Runtime;
utilizing Android.Assist.Design.Widget;
utilizing Android.Assist.V4.View;
utilizing Android.Assist.V4.Widget;
utilizing Android.Assist.V7.App;
utilizing Android.Views;
utilizing Com.Huawei.Hms.Equipment.Consciousness;
utilizing Com.Huawei.Hms.Equipment.Consciousness.Standing;
utilizing Com.Huawei.Hms.Equipment.Consciousness.Standing.Climate;

namespace WeatherAppDemo
{
    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme.NoActionBar")]
    public class MainActivity : AppCompatActivity, NavigationView.IOnNavigationItemSelectedListener
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Necessities.Platform.Init(this, savedInstanceState);
            SetContentView(Useful resource.Structure.activity_main);
            Android.Assist.V7.Widget.Toolbar toolbar = FindViewById(Useful resource.Id.toolbar);
            SetSupportActionBar(toolbar);

          

            DrawerLayout drawer = FindViewById(Useful resource.Id.drawer_layout);
            ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, Useful resource.String.navigation_drawer_open, Useful resource.String.navigation_drawer_close);
            drawer.AddDrawerListener(toggle);
            toggle.SyncState();

            NavigationView navigationView = FindViewById(Useful resource.Id.nav_view);
            navigationView.SetNavigationItemSelectedListener(this);
        }

        personal async void GetWeatherStatus()
        {
            var weatherTask = Consciousness.GetCaptureClient(this).GetWeatherByDeviceAsync();
            await weatherTask;
            if (weatherTask.IsCompleted && weatherTask.Outcome != null)
            {
                IWeatherStatus weatherStatus = weatherTask.Outcome.WeatherStatus;
                WeatherSituation weatherSituation = weatherStatus.WeatherSituation;
                Scenario state of affairs = weatherSituation.Scenario;
                string consequence = $"Metropolis:{weatherSituation.Metropolis.Identify}n";
                consequence += $"Climate id is {state of affairs.WeatherId}n";
                consequence += $"CN Climate id is {state of affairs.CnWeatherId}n";
                consequence += $"Temperature is {state of affairs.TemperatureC}Celcius";
                consequence += $",{state of affairs.TemperatureF}Farenheitn";
                consequence += $"Wind pace is {state of affairs.WindSpeed}km/hn";
                consequence += $"Wind path is {state of affairs.WindDir}n";
                consequence += $"Humidity is {state of affairs.Humidity}%";
            }
            else
            {
                var exception = weatherTask.Exception;
                string errorMessage = $"{AwarenessStatusCodes.GetMessage(exception.GetStatusCode())}: {exception.Message}";
            }
        }

        public override void OnBackPressed()
        {
            DrawerLayout drawer = FindViewById(Useful resource.Id.drawer_layout);
            if(drawer.IsDrawerOpen(GravityCompat.Begin))
            {
                drawer.CloseDrawer(GravityCompat.Begin);
            }
            else
            {
                base.OnBackPressed();
            }
        }

        public override bool OnCreateOptionsMenu(IMenu menu)
        {
            MenuInflater.Inflate(Useful resource.Menu.menu_main, menu);
            return true;
        }

        public override bool OnOptionsItemSelected(IMenuItem merchandise)
        {
            int id = merchandise.ItemId;
            if (id == Useful resource.Id.action_settings)
            {
                return true;
            }

            return base.OnOptionsItemSelected(merchandise);
        }


        public bool OnNavigationItemSelected(IMenuItem merchandise)
        {
            int id = merchandise.ItemId;

            if (id == Useful resource.Id.nav_camera)
            {
                // Deal with the digital camera motion
            }
            else if (id == Useful resource.Id.nav_gallery)
            {

            }
            else if (id == Useful resource.Id.nav_slideshow)
            {

            }
            else if (id == Useful resource.Id.nav_manage)
            {

            }
            else if (id == Useful resource.Id.nav_share)
            {

            }
            else if (id == Useful resource.Id.nav_send)
            {

            }

            DrawerLayout drawer = FindViewById(Useful resource.Id.drawer_layout);
            drawer.CloseDrawer(GravityCompat.Begin);
            return true;
        }
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content material.PM.Permission[] grantResults)
        {
            Xamarin.Necessities.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}

Xamarin App Construct Outcome

  1. Navigate to Resolution Discover > Mission > Proper Click on > Archive/View Archive to generate SHA-256 for construct launch and Click on on Distribute.

  2. Select Distribution Channel > Advert Hoc to signal apk.

  3. Select Demo keystore to launch apk.

  4. Construct succeed and Save apk file.

  5. Lastly right here is the consequence.

Ideas and Methods

1. Consciousness Equipment helps wearable Android gadgets, however HUAWEI HMS Core 4.Zero shouldn’t be deployed on gadgets apart from cellphones. Due to this fact, wearable gadgets should not supported at the moment.

2. Cloud capabilities are required to sense time info and climate.

3. 10012: HMS Core doesn’t have the behaviour recognition permission.

Conclusion

On this article, we’ve got realized combine HMS Climate Consciousness and Account Equipment in Xamarin based mostly Android software. Consumer can simply login and test climate forecast.

Thanks for studying this text.

Be sure you like and feedback to this text, when you discovered it useful. It means rather a lot to me.

References

https://developer.huawei.com/client/en/doc/growth/HMS-Plugin-Guides/sign-in-idtoken-0000001051086088

https://developer.huawei.com/client/en/doc/growth/HMS-Plugin-Guides/service-introduction-0000001062540020

Leave a Reply

Your email address will not be published. Required fields are marked *