How to read IMEI in Dual SIM phone

I am writing an Android app which need to get the IMEI and roaming status from both SIM cards in a Dual SIM phone. I found some Java code to do it. But I don't know how to translate the Java reflection to C# (Even I do it using a Java-C# translator). Here is the link: http://stackoverflow.com/questions/14517338/android-check-whether-the-phone-is-dual-sim/17499889#17499889

Could someone help me?

Answers

  • Below is the code snippet of the functions: getDeviceIdBySlot and getSIMStateBySlot in the TelephonyInfo.java.

    private static String getDeviceIdBySlot(Context context, String predictedMethodName, int slotID) throws GeminiMethodNotFoundException {
    
        String imei = null;
    
        TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    
        try{ 
    
            Class<?> telephonyClass = Class.forName(telephony.getClass().getName());
    
            Class<?>[] parameter = new Class[1];
            parameter[0] = int.class;
            Method getSimID = telephonyClass.getMethod(predictedMethodName, parameter);
    
            Object[] obParameter = new Object[1];
            obParameter[0] = slotID;
            Object ob_phone = getSimID.invoke(telephony, obParameter);
    
            if(ob_phone != null){
                imei = ob_phone.toString();
    
            } 
        } catch (Exception e) {
            e.printStackTrace();
            throw new GeminiMethodNotFoundException(predictedMethodName);
        } 
    
        return imei;
    } 
    
    private static  boolean getSIMStateBySlot(Context context, String predictedMethodName, int slotID) throws GeminiMethodNotFoundException {
    
        boolean isReady = false;
    
        TelephonyManager telephony = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    
        try{ 
    
            Class<?> telephonyClass = Class.forName(telephony.getClass().getName());
    
            Class<?>[] parameter = new Class[1];
            parameter[0] = int.class;
            Method getSimStateGemini = telephonyClass.getMethod(predictedMethodName, parameter);
    
            Object[] obParameter = new Object[1];
            obParameter[0] = slotID;
            Object ob_phone = getSimStateGemini.invoke(telephony, obParameter);
    
            if(ob_phone != null){
                int simState = Integer.parseInt(ob_phone.toString());
                if(simState == TelephonyManager.SIM_STATE_READY){
                    isReady = true;
                } 
            } 
        } catch (Exception e) {
            e.printStackTrace();
            throw new GeminiMethodNotFoundException(predictedMethodName);
        } 
    
        return isReady;
    } 
    
  • alinjojobaalinjojoba INMember ✭✭

    have fun!
    ///


    ///
    ///

    ///

    0/1
    private void GetSIMStateBySlot(int simSlotNum)
    {
    TelephonyManager telemamanger = (TelephonyManager)GetSystemService(Context.TelephonyService);
    string imsi = telemamanger.SimSerialNumber;
            Class telephonyClass = Class.ForName(telemamanger.Class.Name);
             //Java.Lang.Reflect.Method[] methods = telephonyClass.GetMethods();
             //for (int i = 0; i < methods.Length; i++)
             //{
             //    if(methods[i].Name.Contains("serial"))
             //    {
    
             //    }
             //}
            Class[] parameter = new Class[1];
    
            parameter[0] = Java.Lang.Integer.Type;
            Java.Lang.Reflect.Method getSimID = telephonyClass.GetMethod("getSimStateGemini", parameter);
    
            Java.Lang.Object[] obParameter = new Java.Lang.Object[1];
            obParameter[0] = simSlotNum;
            Java.Lang.Object ob_phone = getSimID.Invoke(telemamanger, obParameter);
            string imsi2 = ob_phone.ToString();
    
            MessageBoxAndroid.Show(this, "this is " + imsi2);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="simNum">0/1</param>
        private void GetDeviceImIeBySlot(int simSlotNum)
        {
            TelephonyManager telemamanger = (TelephonyManager)GetSystemService(Context.TelephonyService);
    
            Class telephonyClass = Class.ForName(telemamanger.Class.Name);
            //Java.Lang.Reflect.Method[] methods = telephonyClass.GetMethods();
    
            Class[] parameter = new Class[1];
    
            parameter[0] = Java.Lang.Integer.Type;
            Java.Lang.Reflect.Method getSimID = telephonyClass.GetMethod("getDeviceIdGemini", parameter);
    
            Java.Lang.Object[] obParameter = new Java.Lang.Object[1];
            obParameter[0] = simSlotNum;
            Java.Lang.Object ob_phone = getSimID.Invoke(telemamanger, obParameter);
            string imsi2 = ob_phone.ToString();
            MessageBoxAndroid.Show(this, "this is " + imsi2);
        }
    
  • segunmichealsegunmicheal USMember

    @alinjojoba please i need your help, please i want you to help to translate this code to xamarin c#

    package com.AndroidTelephonyManager;

    import android.app.Activity;
    import android.content.Context;
    import android.os.Bundle;
    import android.telephony.TelephonyManager;
    import android.widget.TextView;

    public class AndroidTelephonyManager extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    TextView textDeviceID = (TextView)findViewById(R.id.deviceid);

    //retrieve a reference to an instance of TelephonyManager
    TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
    
    textDeviceID.setText(getDeviceID(telephonyManager));
    

    }

    String getDeviceID(TelephonyManager phonyManager){

    String id = phonyManager.getDeviceId();
    if (id == null){
    id = "not available";
    }

    int phoneType = phonyManager.getPhoneType();
    switch(phoneType){
    case TelephonyManager.PHONE_TYPE_NONE:
    return "NONE: " + id;

    case TelephonyManager.PHONE_TYPE_GSM:
    return "GSM: IMEI=" + id;

    case TelephonyManager.PHONE_TYPE_CDMA:
    return "CDMA: MEID/ESN=" + id;

    /*
    * for API Level 11 or above
    * case TelephonyManager.PHONE_TYPE_SIP:
    * return "SIP";
    */

    default:
    return "UNKNOWN: ID=" + id;
    }

    }

  • segunmichealsegunmicheal USMember

    for i have try all my method to convert it but is zero - @alinjojoba

  • alinjojobaalinjojoba INMember ✭✭
    edited April 2015

    hi,
    first of all add bellow permission to "AndroidManifest.xml"

    then use the translated to C# code :

    
    using System;
    
    using Android.App;
    using Android.Content;
    using Android.Runtime;
    using Android.Views;
    using Android.Widget;
    using Android.OS;
    using Android.Telephony;
    
    namespace AndroidApplication5
    {
        [Activity(Label = "AndroidApplication5", MainLauncher = true, Icon = "@drawable/icon")]
        public class Activity1 : Activity
        {
            int count = 1;
    
            protected override void OnCreate(Bundle bundle)
            {
                base.OnCreate(bundle);
    
                // Set our view from the "main" layout resource
                SetContentView(Resource.Layout.Main);
    
                // Get our button from the layout resource,
                // and attach an event to it
                Button button = FindViewById<Button>(Resource.Id.MyButton);
    
                button.Click += delegate { button.Text = string.Format("{0} clicks!", count++); };
                //retrieve a reference to an instance of TelephonyManager
                TelephonyManager telephonyManager = (TelephonyManager)GetSystemService(Context.TelephonyService);
    
                string deviceId = getDeviceID(telephonyManager);
            }
            
            private string getDeviceID(TelephonyManager phonyManager)
            {
    
                String id = phonyManager.DeviceId;
                if (id == null)
                {
                    id = "not available";
                }
                PhoneType phoneType = phonyManager.PhoneType;
                switch (phoneType)
                {
                    case PhoneType.None:
                        return "NONE: " + id;
    
                    case PhoneType.Gsm:
                        return "GSM: IMEI=" + id;
    
                    case PhoneType.Cdma:
                        return "CDMA: MEID/ESN=" + id;
    
                    /*
                    * for API Level 11 or above
                    * case TelephonyManager.PHONE_TYPE_SIP:
                    * return "SIP";
                    */
    
                    default:
                        return "UNKNOWN: ID=" + id;
                }
    
    
            }
        }
    }
    
    
    
  • segunmichealsegunmicheal USMember

    Thank a lot - @alinjojoba

  • alinjojobaalinjojoba INMember ✭✭

    have solved ur problem?
    ur welcome.

  • segunmichealsegunmicheal USMember

    Thank a lot - @alinjojoba

  • segunmichealsegunmicheal USMember

    @alinjojoba
    please i want you to help me out again i want to translate this code so that i can achieve what i want to achive in my practice and my career

    for i have try all my effort but is zero

    I will love it if you can Thanks

    here is the code

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.URI;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;
    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.TextView;

    public class ZdeltestEMEIActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    DeviceUuidFactory deviceUuidFactory = new DeviceUuidFactory(this);
    String deviceUuid = deviceUuidFactory.getDeviceUuid().toString();
    Log.d("tgpost",deviceUuid);
    try {
        String webPostAnswer = deviceIdCheck(deviceUuid);
        if (webPostAnswer != null) {
            TextView tv1 = (TextView) findViewById(R.id.textdisplay01);
            TextView tv2 = (TextView) findViewById(R.id.textdisplay02);
            tv1.setText(webPostAnswer);
            tv2.setText(deviceUuid);
            Log.d("tgpost", "okok "+webPostAnswer);
        } else {
            Log.d("tgpost", "nono empty");
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        Log.i("tgpost", "exc  " + e.getMessage());
        Log.i("tgpost", e.toString());
        Log.e("tgpost", e.getStackTrace().toString());
        e.printStackTrace();
    }        
    

    }
    public String deviceIdCheck(String deviceUuidIn) throws Exception {
    boolean flagOK = false;
    BufferedReader in = null;
    try {
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet();
    Log.v("tgpost", "okok");
    //"imei_script.php?deviceId="; + telManager.getDeviceId()
    request.setURI(new URI("http://www.you.net/" +
    "deviceIdCheck.php?deviceId=" + deviceUuidIn
    ));
    HttpResponse response = client.execute(request);
    Log.d("tgpost", "php answered> "+response);
    in = new BufferedReader
    (new InputStreamReader(response.getEntity().getContent()));
    StringBuffer sb = new StringBuffer("");
    String line = "";
    String NL = System.getProperty("line.separator");
    while ((line = in.readLine()) != null) {
    sb.append(line + NL);
    }
    in.close();
    String page = sb.toString();
    Log.d("tgpost", "php answered HUMAN> "+page);
    return page;

    } catch (Exception e) {
        return "problems with connection "+e.getMessage();
    }  
    

    }

    }

  • segunmichealsegunmicheal USMember

    with an addtional class @alinjojoba

  • segunmichealsegunmicheal USMember

    import android.content.Context;
    import android.content.SharedPreferences;
    import android.provider.Settings.Secure;
    import android.telephony.TelephonyManager;
    import java.io.UnsupportedEncodingException;
    import java.util.UUID;

    public class DeviceUuidFactory {
    protected static final String PREFS_FILE = "device_id.xml";
    protected static final String PREFS_DEVICE_ID = "device_id";
    protected static UUID uuid;
    public DeviceUuidFactory(Context context) {
    if( uuid ==null ) {
    synchronized (DeviceUuidFactory.class) {
    if( uuid == null) {
    final SharedPreferences prefs = context.getSharedPreferences( PREFS_FILE, 0);
    final String id = prefs.getString(PREFS_DEVICE_ID, null );
    if (id != null) {
    // Use the ids previously computed and stored in the prefs file
    uuid = UUID.fromString(id);
    } else {
    final String androidId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);

                        // Use the Android ID unless it's broken, in which case fallback on deviceId,
                        // unless it's not available, then fallback on a random number which we store
                        // to a prefs file
                        try {
                            if (!"9774d56d682e549c".equals(androidId)) {
                                uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8"));
                            } else {
                                final String deviceId = ((TelephonyManager) context.getSystemService( Context.TELEPHONY_SERVICE )).getDeviceId();
                                uuid = deviceId!=null ? UUID.nameUUIDFromBytes(deviceId.getBytes("utf8")) : UUID.randomUUID();
                            }
                        } catch (UnsupportedEncodingException e) {
                            throw new RuntimeException(e);
                        }
    
                        // Write the value out to the prefs file
                        prefs.edit().putString(PREFS_DEVICE_ID, uuid.toString() ).commit();
    
                    }
    
                }
            }
        }
    
    }
    
    
    /**
     * Returns a unique UUID for the current android device.  As with all UUIDs, this unique ID is "very highly likely"
     * to be unique across all Android devices.  Much more so than ANDROID_ID is.
     *
     * The UUID is generated by using ANDROID_ID as the base key if appropriate, falling back on
     * TelephonyManager.getDeviceID() if ANDROID_ID is known to be incorrect, and finally falling back
     * on a random UUID that's persisted to SharedPreferences if getDeviceID() does not return a
     * usable value.
     *
     * In some rare circumstances, this ID may change.  In particular, if the device is factory reset a new device ID
     * may be generated.  In addition, if a user upgrades their phone from certain buggy implementations of Android 2.2
     * to a newer, non-buggy version of Android, the device ID may change.  Or, if a user uninstalls your app on
     * a device that has neither a proper Android ID nor a Device ID, this ID may change on reinstallation.
     *
     * Note that if the code falls back on using TelephonyManager.getDeviceId(), the resulting ID will NOT
     * change after a factory reset.  Something to be aware of.
     *
     * Works around a bug in Android 2.2 for many devices when using ANDROID_ID directly.
     *
     * @see http://code.google.com/p/android/issues/detail?id=10603
     *
     * @return a UUID that may be used to uniquely identify your device for most purposes.
     */
    public UUID getDeviceUuid() {
        return uuid;
    }
    
  • segunmichealsegunmicheal USMember

    on the php side: @alinjojoba

    <?php // to return plain text // header("Content-Type: plain/text"); include('/home/public_html/ConnStrDB.php'); $deviceId = $_GET["deviceId"]; $sql = "SELECT Nr_User_Device FROM user_device WHERE Nr_User_Device = '".$deviceId."'"; $result = mysql_query($sql); if ($result) { $row = mysql_fetch_array($result); if ($row[0]) {$deviceIdFile = $row[0];} else {$deviceIdFile = "device not found";} } else { $deviceIdFile = "no check was made, empty set"; } echo $_GET["deviceId"]." ".$deviceIdFile; ?>

    and (so that you dont have to insert the numbers manually (just change the php fileName in the submit):

    <?php // to return plain text // header("Content-Type: plain/text"); include('/home/public_html/ConnStrDB.php'); $deviceId = $_GET["deviceId"]; $sql = "SELECT Nr_User_Device, Ic_User_Device_Status FROM user_device WHERE Nr_User_Device = ".$deviceId; $sql = "INSERT INTO user_device (Nr_User_Device) VALUES ('".$deviceId."')"; $result = mysql_query($sql); if ($result) { $deviceIdFile = "device inserted"; } else { $deviceIdFile = "not inserted"; } echo $_GET["deviceId"]." ".$deviceIdFile; ?>
Sign In or Register to comment.