0

In my application, I need to get device Id. I use the following:

var DeviceId=Resolver.Resolve<IDevice>().Id;

Every things was normal when I set Target Android version to Android 8.0 (API level 26 - Oreo) or lower versions. However, When I want to update my application, Google Play stipulated that the Target Android version must be Android 9.0 (API level 28 - Pie). So when I change the Target Android version I get unknown value for device Id.

What is the problem?

Ahmed Shamel
  • 1,982
  • 3
  • 24
  • 58
  • Can you share the code where you are actually getting this device id? The natively injected code basically – FreakyAli Nov 28 '19 at 13:18
  • 1
    You could use the code below to get the device ID. `Android.Provider.Settings.Secure.GetString(Android.App.Application.Context.ContentResolver, Android.Provider.Settings.Secure.AndroidId);` If you want to know what is wrong with your code, please share more code for us to test. – Wendy Zang - MSFT Nov 29 '19 at 01:42

2 Answers2

1

It seems that XLabs.Forms use the following code to get Id (for Android):

Build.Serial;

On Android 8 (SDK 26) and above, this field will return UNKNOWN and must be accessed with:

Build.getSerial();

which requires the dangerous permission android.permission.READ_PHONE_STATE.

More details: Android: How to programmatically access the device serial number shown in the AVD manager (API Version 8)

Ahmed Shamel
  • 1,982
  • 3
  • 24
  • 58
0

I had the same problem, and solved it as follows:

In my MainActivity.cs file i defined

public static ContentResolver myContentResolver;

and set its value in the OnCreate method

protected override void OnCreate(Bundle bundle)
{
    TabLayoutResource = Resource.Layout.Tabbar;
    ToolbarResource = Resource.Layout.Toolbar;
    base.OnCreate(bundle);

    global::Xamarin.Forms.Forms.Init(this, bundle);
    LoadApplication(new App());

    // Getting ContentResolver instance
    myContentResolver = this.ContentResolver;
}

And then my GetDeviceId

public String GetDeviceId()
{

    String deviceID = Android.OS.Build.Serial?.ToString();

    if (String.IsNullOrEmpty(deviceID) || deviceID.ToUpper() == "UNKNOWN") // Android 9 returns "Unknown"
    {

        ContentResolver myContentResolver = MyApp.Droid.MainActivity.myContentResolver;

        deviceID = Android.Provider.Settings.Secure.GetString(myContentResolver, Android.Provider.Settings.Secure.AndroidId);

    }


    return deviceID;

}
deczaloth
  • 7,094
  • 4
  • 24
  • 59