Hi all Android developers!
I have just started exploring and learning how to make Android native plugins for Unity. I got my test plugin up and running yesterday just to get random number from the plugin into Unity project that can be compiled and ran on an Android device. Now I started to up my game and try something more dramatic, that being try to read from the phone what is the SIM card serial number using getSimSerialNumber() but unfortunately on any device I try it, it returns null.
Can someone more seasoned help me out understanding what is going wrong?
I first thought I need to create new custom Manifest, just to have permission for READ_PHONE_STATE, but after I made my own Manifest the app does not even launch, it crashes when you try to run. Fortunately enough it seems after investigation that Unity 5.1 adds that permission automatically to its default manifest. And by checking my project stagingarea manifest it is requesting for that permission. So apparently the manifest is not the problem.
Here is my Android Java project code:
package com.Test.myandroidplugin;
import java.util.Random;
import android.app.Activity;
import android.content.Context;
import android.telephony.TelephonyManager;
public class AndroidPluginAccess extends Activity
{
public static int ReturnRandomInt()
{
int randInt = new Random().nextInt(100);
return randInt;
}
public String ReturnSIMSerialNumber()
{
TelephonyManager mTelephonyMgr =
(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String serialString = mTelephonyMgr.getSimSerialNumber();
return serialString;
}
}
And here is my Unity test script:
using UnityEngine;
using System.Collections;
public class GetAndroidPluginData : MonoBehaviour
{
private int randomValueFromAndroid = -1;
private string serialNumberFromAndroid = "-1";
#if UNITY_ANDROID
public static int ReturnRandomInt()
{
AndroidJavaClass myAndroidJavaClass =
new AndroidJavaClass("com.Test.myandroidplugin.AndroidPluginAccess");
return myAndroidJavaClass.CallStatic<int>("ReturnRandomInt");
}
public string ReturnSIMSerialNumber()
{
AndroidJavaClass myAndroidJavaClass =
new AndroidJavaClass("com.Test.myandroidplugin.AndroidPluginAccess");
return myAndroidJavaClass.Call<string>("ReturnSIMSerialNumber");
}
#endif
public void LogAndroidData ()
{
#if UNITY_ANDROID
randomValueFromAndroid = ReturnRandomInt();
serialNumberFromAndroid = ReturnSIMSerialNumber();
#endif
Debug.Log ("Value returned from Android: " + randomValueFromAndroid );
Debug.Log ("Serial returned from Android: " + serialNumberFromAndroid );
}
}
When I deploy to my tablet, the random value is just fine. I call the method from UI and I get new random value. But the SIM card serial number is null on my tablet that has SIM card for 4G and also on Samsung S4 mobile phone that has SIM card.
Anyone can see if I do something just in a wrong way and that is why I get null?