Search code examples
xamarinandroid-activityxamarin.androidhce

How to import Activity of NfcFCardEmulation.EnableService from Xamarin common project, not Android project?


I'm developing an app using Xamarin's HCE feature. The project structure is as follows. hceSample hceSample.Android hceSample.iOS

I am implementing hce simulation code called hceService in hceSample, not hceSample.Android. A function called Enable_Card exists in the hce service, and you want to use the NfcFCardEmulation.EnableService function in that function. Activity and ComponentName are requested as parameters of the function. The ComponentName area was handled easily, but I don't know how to get the Activity. Please advise.

This is the contents of enable_Card function of hceService.

private Activity activity = null;
private bool enable_Card(cardModel card)
        {
            try
            {
                sid = card.cardSN;
                tag = "Felica";
                emulation.EnableService(, componentName); //<- How to get Activity??
                emulation.SetNfcid2ForService(componentName, sid);

                return true;
            }
            catch
            {
                return false;
            }
        }

This is my first time asking a question on Stackoverflow. I would appreciate it if you could point out any missing or incorrect parts.

I trying this

  1. activity = Xamarin.Essentials.Platform.CurrentActivity; //<- this function is not found!

Added missing information! The namespace of the Enable_Card function is located in hceSample.Service.


Solution

  • Are you using the NfcFCardEmulation.EnableService(Activity, ComponentName) Method, right?

    The method is an android api from android sdk,you cannot use it directly in xamarin.form(yours is hceSample) project.

    If you want to call the function in xamarin form project(hceSample) from native platform(hceSample.Android, or hceSample.iOS),you can use Xamarin.Forms DependencyService to achieve this.

    The DependencyService class is a service locator that enables Xamarin.Forms applications to invoke native platform functionality from shared code.

    For more information about DependencyService, you can check document Xamarin.Forms DependencyService. And there is a sample included in above document,which is helpful for you to understand DependencyService.

    Note:

    We recognize that hardware service is the right and ideal way to implement in each OS project. However, I'm curious if there is a way to code Android and iOS at the same time

    Since the api you used is from android sdk, you can call it in native android or use DependencyService to call it on xamarin.form(yours is hceSample) project.

    If you call it on xamarin.form(yours is hceSample) project, you also need to find the the corresponding function or interface in iOS.