Example usage for android.telephony TelephonyManager getDeviceId

List of usage examples for android.telephony TelephonyManager getDeviceId

Introduction

In this page you can find the example usage for android.telephony TelephonyManager getDeviceId.

Prototype

@Deprecated
@SuppressAutoDoc 
@RequiresPermission(android.Manifest.permission.READ_PHONE_STATE)
public String getDeviceId() 

Source Link

Document

Returns the unique device ID, for example, the IMEI for GSM and the MEID or ESN for CDMA phones.

Usage

From source file:com.mb.android.MainActivity.java

@android.webkit.JavascriptInterface
@org.xwalk.core.JavascriptInterface/*w  ww. j  av a 2 s.c  om*/
public String getLegacyDeviceId() {

    Context context = getApplicationContext();
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

    String uuid;
    String androidID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
    String deviceID = tm.getDeviceId();
    String simID = tm.getSimSerialNumber();

    if ("9774d56d682e549c".equals(androidID) || androidID == null) {
        androidID = "";
    }

    if (deviceID == null) {
        deviceID = "";
    }

    if (simID == null) {
        simID = "";
    }

    uuid = androidID + deviceID + simID;
    uuid = String.format("%32s", uuid).replace(' ', '0');
    uuid = uuid.substring(0, 32);
    uuid = uuid.replaceAll("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5");

    return uuid;
}

From source file:com.yozio.android.YozioHelper.java

private void setCarrierMobileAndDeviceInfo() {
    SharedPreferences settings = context.getSharedPreferences("yozioPreferences", 0);

    try {//from   w  w  w  . j  a v a2s  . c  om
        TelephonyManager telephonyManager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        carrierName = telephonyManager.getNetworkOperatorName();
        carrierCountryCode = telephonyManager.getNetworkCountryIso();

        if (telephonyManager.getNetworkOperator() != null
                && (telephonyManager.getNetworkOperator().length() == 5
                        || telephonyManager.getNetworkOperator().length() == 6)) {
            mobileCountryCode = telephonyManager.getNetworkOperator().substring(0, 3);
            mobileNetworkCode = telephonyManager.getNetworkOperator().substring(3);
        }

        deviceId = telephonyManager.getDeviceId();

        if (!isValidDeviceId(deviceId)) {
            // Fetch the emulator device ID from the preferences
            deviceId = settings.getString("emulatorDeviceId", null);
        }

        if (!isValidDeviceId(deviceId)) {
            StringBuffer buff = new StringBuffer();
            buff.append("emulator");

            String chars = "1234567890abcdefghijklmnopqrstuvw";
            int ccLength = chars.length() - 1;

            for (int i = 0; i < 32; i++) {
                int index = (int) (Math.random() * ccLength);
                buff.append(chars.charAt(index));
            }

            SharedPreferences.Editor editor = settings.edit();
            editor.putString("emulatorDeviceId", deviceId);
            editor.commit();

            deviceId = buff.toString();
        }

        deviceId = deviceId.toLowerCase();
    } catch (Exception e) {
        deviceId = null;
    }
}

From source file:com.att.android.arodatacollector.main.AROCollectorService.java

/**
 * Gets processing when an AROCollectorService object is created.
 * Overrides the android.app.Service#onCreate method.
 * //from   www .  j ava  2  s .co m
 * @see android.app.Service#onCreate()
 */
@Override
public void onCreate() {

    // Initializes the data controls and starts the Data Collector trace
    // (i.e tcpdump,VideoCapture)
    mDataCollectorService = this;
    mApp = (ARODataCollector) getApplication();
    mAroUtils = new AROCollectorUtils();

    //flurry start session if set to is true.  set to false to disable FlurryAgent logging call.
    FlurryAgent.setLogEvents(isFlurryLogEventsEnabled);

    //check for flurry api key override from default-incorrect key will cause session to not log to correct Flurry app.
    setFlurryApiKey();
    FlurryAgent.setContinueSessionMillis(5000); // Set session timeout to 5 seconds (minimum specified by flurry)

    FlurryAgent.onStartSession(this, mApp.app_flurry_api_key); //don't use mAroCollectorService as context
    if (DEBUG) {
        Log.d(TAG, "onCreate called: " + mAroUtils.getSystemTimeinSeconds());
        Log.d(TAG, "flurry-called onStartSession");
    }

    //set device id as flurry's userid within a session
    final TelephonyManager mAROtelManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    FlurryAgent.setUserId(mAROtelManager.getDeviceId());
    if (DEBUG) {
        Log.d(TAG, "flurry-TelephonyManager deviceId: " + mAROtelManager.getDeviceId());
    }
    disableScreenTimeout();
    TRACE_FOLDERNAME = mApp.getDumpTraceFolderName();
    mVideoRecording = mApp.getCollectVideoOption();
    startDataCollectorVideoCapture();
    statDataCollectortcpdumpCapture();
    startDataCollectorDmesgCapture();
}

From source file:research.dlsu.cacaoapp.Camera2BasicFragment1.java

public void saveDeviceIdToSharedPreferences() {
    SharedPreferences sp = getActivity().getSharedPreferences(SharedPreferencesFile.SP_NAME,
            getActivity().MODE_PRIVATE);
    if (sp.getString(SharedPreferencesFile.ATTRIBUTE_SERIALNUMBER, null) == null) {
        SharedPreferences.Editor spEditor = sp.edit();
        TelephonyManager telephonyManager = (TelephonyManager) getActivity()
                .getSystemService(Context.TELEPHONY_SERVICE);
        spEditor.putString(SharedPreferencesFile.ATTRIBUTE_SERIALNUMBER, telephonyManager.getDeviceId());
        spEditor.commit();//from www.  ja  v  a 2  s . co m
    }
}

From source file:app.clirnet.com.clirnetapp.activity.LoginActivity.java

private void checkLogin(final String email, final String password, final String docMemId, final String docId) {

    String tag_string_req = "req_login";

    showProgressDialog();//w w w .j  av a 2 s .  c  om
    // showDialog();

    StringRequest strReq = new StringRequest(Request.Method.POST, AppConfig.URL_LOGIN,
            new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {

                    // Log.e("Loginresponse", " " + response);

                    if (LoginActivity.this.isDestroyed()) { // or call isFinishing() if min sdk version < 17
                        return;
                    }
                    dismissProgressDialog();

                    try {
                        JSONObject jObj = new JSONObject(response);

                        AppController appController = new AppController();
                        String end_time = appController.getDateTimenew();

                        // Create login session
                        JSONObject user = jObj.getJSONObject("data");
                        String result = user.getString("result");
                        String msg = user.getString("msg");
                        String response_end_time = user.getString("process_end_time");
                        appController.appendLog(
                                appController.getDateTime() + " " + "/ " + "Login Async Task:  Message :" + msg
                                        + "  Result : " + result + " response_end_time:  " + response_end_time
                                        + " " + Thread.currentThread().getStackTrace()[2].getLineNumber());

                        if (result.equals("true")) {

                            dbController.addLoginRecord(email, password, phoneNumber);

                            getTermsAndCondition();
                            //update last sync time if sync from server
                            lastSyncTime(end_time);

                        } else {

                            appController.showToastMsg(getApplicationContext(), "Username/Password Mismatch");
                            //Toast.makeText(mContext, "Username/Password Mismatch", Toast.LENGTH_SHORT).show();
                        }

                    } catch (JSONException | ClirNetAppException e) {
                        // JSON error
                        e.printStackTrace();
                        new AppController().appendLog(new AppController().getDateTime() + " " + "/ "
                                + "Login Async Task" + e + " Line Number: "
                                + Thread.currentThread().getStackTrace()[2].getLineNumber());
                    } finally {
                        if (dbController != null) {
                            dbController.close();
                        }

                    }
                }

            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    //Toast.makeText(mContext, " " +error.getMessage(), Toast.LENGTH_SHORT).show();
                    dismissProgressDialog();
                }
            }) {

        @Override
        protected Map<String, String> getParams() {

            TelephonyManager manager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
            String imeiNo = manager.getDeviceId();
            // Posting parameters to login url
            Map<String, String> params = new HashMap<>();
            String keyid = getResources().getString(R.string.apikey);
            String fcm_id = FirebaseInstanceId.getInstance().getToken();
            params.put("username", email);
            params.put("password", password);
            params.put("apikey", keyid);
            params.put("process_start_time", start_time);
            params.put("fcm_id", fcm_id);
            params.put("membershipid", docMemId);
            params.put("docId", docId);
            params.put("imei_no", imeiNo);
            return checkParams(params);
        }

        private Map<String, String> checkParams(Map<String, String> map) {
            for (Map.Entry<String, String> pairs : map.entrySet()) {
                if (pairs.getValue() == null) {
                    map.put(pairs.getKey(), "");
                }
            }
            return map;
        }
    };
    int socketTimeout = 30000;//30 seconds - change to what you want
    int retryforTimes = 2;
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, retryforTimes,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    strReq.setRetryPolicy(policy);
    AppController.getInstance().setPriority(Request.Priority.HIGH);
    // Adding request to request queue
    strReq.setShouldCache(false);//set cache false

    AppController.getInstance().getRequestQueue().getCache().clear(); //removing all previous cache
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

}

From source file:research.sg.edu.edapp.kb.KbSoftKeyboard.java

/**
 * This is the point where you can do all of your UI initialization.  It
 * is called after creation and any configuration change.
 *//*  w  w w . j  a va2 s.co  m*/
@Override
public void onInitializeInterface() {
    if (mQwertyKeyboard != null) {
        // Configuration changes can happen after the keyboard gets recreated,
        // so we need to be able to re-build the keyboards if the available
        // space has changed.
        int displayWidth = getMaxWidth();
        if (displayWidth == mLastDisplayWidth)
            return;
        mLastDisplayWidth = displayWidth;
    }
    mQwertyKeyboard = new KbLatinKeyboard(this, R.xml.qwerty);
    mSymbolsKeyboard = new KbLatinKeyboard(this, R.xml.symbols);
    mSymbolsShiftedKeyboard = new KbLatinKeyboard(this, R.xml.symbols_shift);
    sdCardRoot = Environment.getExternalStorageDirectory();
    dataDir = new File(sdCardRoot, getResources().getString(R.string.data_file_path));

    if (!dataDir.exists()) {
        dataDir.mkdirs();
    }

    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    imei_no = (String) telephonyManager.getDeviceId();
}

From source file:org.wso2.emm.agent.services.DeviceInfoPayload.java

/**
 * Fetch all device runtime information.
 * @throws AndroidAgentException/*from  w  w  w.j  a  va 2 s.c  om*/
 */
private void getInfo() throws AndroidAgentException {

    TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

    Location deviceLocation = locationService.getLastKnownLocation();
    if (device == null) {
        device = new Device();
    }
    deviceInfo = new DeviceInfo(context);
    Power power = phoneState.getBatteryDetails();
    device.setDeviceIdentifier(deviceInfo.getDeviceId());
    device.setDescription(deviceInfo.getDeviceName());
    device.setName(deviceInfo.getDeviceName());

    List<Device.Property> properties = new ArrayList<>();

    Device.Property property = new Device.Property();
    property.setName(Constants.Device.SERIAL);
    property.setValue(deviceInfo.getDeviceSerialNumber());
    properties.add(property);

    property = new Device.Property();
    property.setName(Constants.Device.IMEI);
    property.setValue(telephonyManager.getDeviceId());
    properties.add(property);

    property = new Device.Property();
    property.setName(Constants.Device.IMSI);
    property.setValue(deviceInfo.getIMSINumber());
    properties.add(property);

    property = new Device.Property();
    property.setName(Constants.Device.MAC);
    property.setValue(deviceInfo.getMACAddress());
    properties.add(property);

    property = new Device.Property();
    property.setName(Constants.Device.MODEL);
    property.setValue(deviceInfo.getDeviceModel());
    properties.add(property);

    property = new Device.Property();
    property.setName(Constants.Device.VENDOR);
    property.setValue(deviceInfo.getDeviceManufacturer());
    properties.add(property);

    property = new Device.Property();
    property.setName(Constants.Device.OS);
    property.setValue(deviceInfo.getOsVersion());
    properties.add(property);

    property = new Device.Property();
    property.setName(Constants.Device.OS_BUILD_DATE);
    property.setValue(deviceInfo.getOSBuildDate());
    properties.add(property);

    property = new Device.Property();
    property.setName(Constants.Device.NAME);
    property.setValue(deviceInfo.getDeviceName());
    properties.add(property);

    if (deviceLocation != null) {
        double latitude = deviceLocation.getLatitude();
        double longitude = deviceLocation.getLongitude();

        if (latitude != 0 && longitude != 0) {
            property = new Device.Property();
            property.setName(Constants.Device.MOBILE_DEVICE_LATITUDE);
            property.setValue(String.valueOf(latitude));
            properties.add(property);

            property = new Device.Property();
            property.setName(Constants.Device.MOBILE_DEVICE_LONGITUDE);
            property.setValue(String.valueOf(longitude));
            properties.add(property);
        }
    }

    if (registrationId != null) {
        property = new Device.Property();
        property.setName(Constants.Device.GCM_TOKEN);
        property.setValue(registrationId);
        properties.add(property);
    }

    List<Device.Property> deviceInfoProperties = new ArrayList<>();

    property = new Device.Property();
    property.setName(Constants.Device.ENCRYPTION_STATUS);
    property.setValue(String.valueOf(deviceInfo.isEncryptionEnabled()));
    deviceInfoProperties.add(property);

    if ((deviceInfo.getSdkVersion() >= Build.VERSION_CODES.LOLLIPOP)) {
        property = new Device.Property();
        property.setName(Constants.Device.PASSCODE_STATUS);
        property.setValue(String.valueOf(deviceInfo.isPasscodeEnabled()));
        deviceInfoProperties.add(property);
    }

    property = new Device.Property();
    property.setName(Constants.Device.BATTERY_LEVEL);
    int batteryLevel = Math.round(power.getLevel());
    property.setValue(String.valueOf(batteryLevel));
    deviceInfoProperties.add(property);

    property = new Device.Property();
    property.setName(Constants.Device.MEMORY_INFO_INTERNAL_TOTAL);
    property.setValue(String.valueOf(phoneState.getTotalInternalMemorySize()));
    deviceInfoProperties.add(property);

    property = new Device.Property();
    property.setName(Constants.Device.MEMORY_INFO_INTERNAL_AVAILABLE);
    property.setValue(String.valueOf(phoneState.getAvailableInternalMemorySize()));
    deviceInfoProperties.add(property);

    property = new Device.Property();
    property.setName(Constants.Device.MEMORY_INFO_EXTERNAL_TOTAL);
    property.setValue(String.valueOf(phoneState.getTotalExternalMemorySize()));
    deviceInfoProperties.add(property);

    property = new Device.Property();
    property.setName(Constants.Device.MEMORY_INFO_EXTERNAL_AVAILABLE);
    property.setValue(String.valueOf(phoneState.getAvailableExternalMemorySize()));
    deviceInfoProperties.add(property);

    property = new Device.Property();
    property.setName(Constants.Device.NETWORK_OPERATOR);
    property.setValue(String.valueOf(deviceInfo.getNetworkOperatorName()));
    deviceInfoProperties.add(property);

    property = new Device.Property();
    property.setName(Constants.Device.PHONE_NUMBER);
    String mPhoneNumber = telephonyManager.getLine1Number();
    property.setValue(mPhoneNumber);
    deviceInfoProperties.add(property);

    DeviceNetworkStatus deviceNetworkStatus = DeviceNetworkStatus.getInstance(context);
    if (deviceNetworkStatus.isConnectedMobile()) {
        telephonyManager.listen(deviceNetworkStatus, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
    }

    String network = deviceNetworkStatus.getNetworkStatus();
    if (network != null) {
        property = new Device.Property();
        property.setName(Constants.Device.NETWORK_INFO);
        property.setValue(network);
        properties.add(property);
    }

    // adding wifi scan results..
    property = new Device.Property();
    property.setName(Constants.Device.WIFI_SCAN_RESULT);
    property.setValue(deviceNetworkStatus.getWifiScanResult());
    properties.add(property);

    RuntimeInfo runtimeInfo = new RuntimeInfo(context);
    String cpuInfoPayload;
    try {
        cpuInfoPayload = mapper.writeValueAsString(runtimeInfo.getCPUInfo());
    } catch (JsonProcessingException e) {
        String errorMsg = "Error occurred while parsing property CPU info object to json.";
        Log.e(TAG, errorMsg, e);
        throw new AndroidAgentException(errorMsg, e);
    }

    property = new Device.Property();
    property.setName(Constants.Device.CPU_INFO);
    property.setValue(cpuInfoPayload);
    properties.add(property);

    String ramInfoPayload;
    try {
        ramInfoPayload = mapper.writeValueAsString(runtimeInfo.getRAMInfo());
    } catch (JsonProcessingException e) {
        String errorMsg = "Error occurred while parsing property RAM info object to json.";
        Log.e(TAG, errorMsg, e);
        throw new AndroidAgentException(errorMsg, e);
    }

    property = new Device.Property();
    property.setName(Constants.Device.RAM_INFO);
    property.setValue(ramInfoPayload);
    properties.add(property);

    List<Device.Property> batteryProperties = new ArrayList<>();
    property = new Device.Property();
    property.setName(Constants.Device.BATTERY_LEVEL);
    property.setValue(String.valueOf(power.getLevel()));
    batteryProperties.add(property);

    property = new Device.Property();
    property.setName(Constants.Device.SCALE);
    property.setValue(String.valueOf(power.getScale()));
    batteryProperties.add(property);

    property = new Device.Property();
    property.setName(Constants.Device.BATTERY_VOLTAGE);
    property.setValue(String.valueOf(power.getVoltage()));
    batteryProperties.add(property);

    property = new Device.Property();
    property.setName(Constants.Device.HEALTH);
    property.setValue(String.valueOf(power.getHealth()));
    batteryProperties.add(property);

    property = new Device.Property();
    property.setName(Constants.Device.STATUS);
    property.setValue(String.valueOf(power.getStatus()));
    batteryProperties.add(property);

    property = new Device.Property();
    property.setName(Constants.Device.PLUGGED);
    property.setValue(String.valueOf(power.getPlugged()));
    batteryProperties.add(property);

    String batteryInfoPayload;
    try {
        batteryInfoPayload = mapper.writeValueAsString(batteryProperties);
    } catch (JsonProcessingException e) {
        String errorMsg = "Error occurred while parsing property battery info object to json.";
        Log.e(TAG, errorMsg, e);
        throw new AndroidAgentException(errorMsg, e);
    }

    property = new Device.Property();
    property.setName(Constants.Device.BATTERY_INFO);
    property.setValue(batteryInfoPayload);
    properties.add(property);

    // building device info json payload
    String deviceInfoPayload;
    try {
        deviceInfoPayload = mapper.writeValueAsString(deviceInfoProperties);
    } catch (JsonProcessingException e) {
        String errorMsg = "Error occurred while parsing property object to json.";
        Log.e(TAG, errorMsg, e);
        throw new AndroidAgentException(errorMsg, e);
    }
    property = new Device.Property();
    property.setName(Constants.Device.INFO);
    property.setValue(deviceInfoPayload);
    properties.add(property);

    device.setProperties(properties);
}

From source file:com.speedtong.example.ui.chatting.ChattingActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    LogUtil.d(TAG, "onCreate");
    super.onCreate(savedInstanceState);
    brand = Build.MODEL + Build.BRAND;/*from   w w  w.j a va  2 s . co m*/
    TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    uuid = tm.getDeviceId();
    messageDao = MessageDao.getInstance(this);
    toast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
    sdpath = Environment.getExternalStorageDirectory().getAbsolutePath();

    // ???
    initView();
    // ???
    initActivityState(savedInstanceState);

    final ArrayList<ECMessage> list = IMessageSqlManager.queryIMessageList(mThread, 20,
            getMessageAdapterLastMessageTime() + "");
    mListView.post(new Runnable() {

        @Override
        public void run() {
            mChattingAdapter.setData(list);
            if (mChattingAdapter.getCount() < 20) {
                //mPullDownView.setPullEnabled(false);
                //mPullDownView.setPullViewVisibed(false);
            }
            mListView.clearFocus();
            mChattingAdapter.notifyDataSetChanged();
            mListView.setSelection(mChattingAdapter.getCount());
        }
    });

    // ?IM?API
    mChatManager = SDKCoreHelper.getECChatManager();
    HandlerThread thread = new HandlerThread("ChattingVoiceRecord", Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();

    // Get the HandlerThread's Looper and use it for our Handler
    mChattingLooper = thread.getLooper();
    mVoiceHandler = new Handler(mChattingLooper);
    mVoiceHandler.post(new Runnable() {

        @Override
        public void run() {
            doEmojiPanel();
        }
    });
}

From source file:com.tapjoy.TapjoyConnectCore.java

/**
 * Initialize data from the device information and application info.
 * This data is used in our URL connection to the Tapjoy server. 
 *///from  w ww. j ava 2s.c  o m
private void init() {
    PackageManager manager = context.getPackageManager();

    try {
        // ANDROID_ID
        androidID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);

        // Get app version.
        PackageInfo packageInfo = manager.getPackageInfo(context.getPackageName(), 0);
        appVersion = packageInfo.versionName;

        // Device platform.  Same as device type.
        deviceType = TapjoyConstants.TJC_DEVICE_PLATFORM_TYPE;
        platformName = TapjoyConstants.TJC_DEVICE_PLATFORM_TYPE;

        // Get the device model.
        deviceModel = android.os.Build.MODEL;
        deviceManufacturer = android.os.Build.MANUFACTURER;

        // Get the Android OS Version.
        deviceOSVersion = android.os.Build.VERSION.RELEASE;

        // Get the device country and language code.
        deviceCountryCode = Locale.getDefault().getCountry();
        deviceLanguage = Locale.getDefault().getLanguage();

        // Tapjoy SDK Library version.
        libraryVersion = TapjoyConstants.TJC_LIBRARY_VERSION_NUMBER;

        SharedPreferences settings = context.getSharedPreferences(TapjoyConstants.TJC_PREFERENCE, 0);

        try {
            TelephonyManager telephonyManager = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);

            if (telephonyManager != null) {
                deviceID = telephonyManager.getDeviceId();

                carrierName = telephonyManager.getNetworkOperatorName();
                carrierCountryCode = telephonyManager.getNetworkCountryIso();

                // getNetworkOperator() returns MCC + MNC, so make sure it's 5 or 6 digits total.
                // MCC is 3 digits
                // MNC is 2 or 3 digits
                if (telephonyManager.getNetworkOperator() != null
                        && (telephonyManager.getNetworkOperator().length() == 5
                                || telephonyManager.getNetworkOperator().length() == 6)) {
                    mobileCountryCode = telephonyManager.getNetworkOperator().substring(0, 3);
                    mobileNetworkCode = telephonyManager.getNetworkOperator().substring(3);
                }
            }

            TapjoyLog.i(TAPJOY_CONNECT, "deviceID: " + deviceID);

            boolean invalidDeviceID = false;

            //----------------------------------------
            // Is the device ID null or empty?
            //----------------------------------------
            if (deviceID == null) {
                TapjoyLog.e(TAPJOY_CONNECT, "Device id is null.");
                invalidDeviceID = true;
            } else
            //----------------------------------------
            // Is this an emulator device ID?
            //----------------------------------------
            if (deviceID.length() == 0 || deviceID.equals("000000000000000") || deviceID.equals("0")) {
                TapjoyLog.e(TAPJOY_CONNECT, "Device id is empty or an emulator.");
                invalidDeviceID = true;
            }
            //----------------------------------------
            // Valid device ID.
            //----------------------------------------
            else {
                // Lower case the device ID.
                deviceID = deviceID.toLowerCase();
            }

            TapjoyLog.i(TAPJOY_CONNECT, "ANDROID SDK VERSION: " + android.os.Build.VERSION.SDK);

            // Is this at least Android 2.3+?
            // Then let's get the serial.
            if (Integer.parseInt(android.os.Build.VERSION.SDK) >= 9) {
                TapjoyLog.i(TAPJOY_CONNECT, "TRYING TO GET SERIAL OF 2.3+ DEVICE...");

                // THIS CLASS IS ONLY LOADED FOR ANDROID 2.3+
                TapjoyHardwareUtil hardware = new TapjoyHardwareUtil();

                serialID = hardware.getSerial();

                // Is there no IMEI or MEID?
                if (invalidDeviceID) {
                    deviceID = serialID;
                }

                TapjoyLog.i(TAPJOY_CONNECT, "====================");
                TapjoyLog.i(TAPJOY_CONNECT, "SERIAL: deviceID: [" + deviceID + "]");
                TapjoyLog.i(TAPJOY_CONNECT, "====================");

                //----------------------------------------
                // Is the device ID null or empty?
                //----------------------------------------
                if (deviceID == null) {
                    TapjoyLog.e(TAPJOY_CONNECT, "SERIAL: Device id is null.");
                    invalidDeviceID = true;
                } else
                //----------------------------------------
                // Is this an emulator device ID?
                //----------------------------------------
                if (deviceID.length() == 0 || deviceID.equals("000000000000000") || deviceID.equals("0")
                        || deviceID.equals("unknown")) {
                    TapjoyLog.e(TAPJOY_CONNECT, "SERIAL: Device id is empty or an emulator.");
                    invalidDeviceID = true;
                }
                //----------------------------------------
                // Valid device ID.
                //----------------------------------------
                else {
                    // Lower case the device ID.
                    deviceID = deviceID.toLowerCase();
                    invalidDeviceID = false;
                }
            }

            // Is the device ID invalid?  This is probably an emulator or pre-production device.
            if (invalidDeviceID) {
                StringBuffer buff = new StringBuffer();
                buff.append("EMULATOR");
                String deviceId = settings.getString(TapjoyConstants.PREF_EMULATOR_DEVICE_ID, null);

                // Do we already have an emulator device id stored for this device?
                if (deviceId != null && !deviceId.equals("")) {
                    deviceID = deviceId;
                }
                // Otherwise generate a deviceID for emulator testing.
                else {
                    String constantChars = "1234567890abcdefghijklmnopqrstuvw";

                    for (int i = 0; i < 32; i++) {
                        int randomChar = (int) (Math.random() * 100);
                        int ch = randomChar % 30;
                        buff.append(constantChars.charAt(ch));
                    }

                    deviceID = buff.toString().toLowerCase();

                    // Save the emulator device ID in the prefs so we can reuse it.
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putString(TapjoyConstants.PREF_EMULATOR_DEVICE_ID, deviceID);
                    editor.commit();
                }
            }
        } catch (Exception e) {
            TapjoyLog.e(TAPJOY_CONNECT, "Error getting deviceID. e: " + e.toString());
            deviceID = null;
        }

        // Set the userID to the deviceID as the initial value.
        if (userID.length() == 0)
            userID = deviceID;

        // Save the SHA-2 hash of the device id.
        sha2DeviceID = TapjoyUtil.SHA256(deviceID);

        // Get screen density, dimensions and layout.
        try {
            // This is a backwards compatibility fix for Android 1.5 which has no display metric API.
            // If this is 1.6 or higher, then load the class, otherwise the class never loads and
            // no crash occurs.
            if (Integer.parseInt(android.os.Build.VERSION.SDK) > 3) {
                TapjoyDisplayMetricsUtil displayMetricsUtil = new TapjoyDisplayMetricsUtil(context);

                deviceScreenDensity = "" + displayMetricsUtil.getScreenDensity();
                deviceScreenLayoutSize = "" + displayMetricsUtil.getScreenLayoutSize();
            }
        } catch (Exception e) {
            TapjoyLog.e(TAPJOY_CONNECT, "Error getting screen density/dimensions/layout: " + e.toString());
        }

        // Get mac address.
        try {
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

            if (wifiManager != null) {
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();

                if (wifiInfo != null) {
                    macAddress = wifiInfo.getMacAddress();

                    if (macAddress != null && macAddress.length() > 0) {
                        macAddress = macAddress.toUpperCase();
                        sha1MacAddress = TapjoyUtil.SHA1(macAddress);
                    }
                }
            }
        } catch (Exception e) {
            TapjoyLog.e(TAPJOY_CONNECT, "Error getting device mac address: " + e.toString());
        }

        // Alternate market.
        if (getFlagValue(TapjoyConnectFlag.ALTERNATE_MARKET) != null) {
            marketName = getFlagValue(TapjoyConnectFlag.ALTERNATE_MARKET);

            // Check for existing/supported market names.
            ArrayList<String> supportedMarketNames = new ArrayList<String>();
            supportedMarketNames.add(TapjoyConnectFlag.MARKET_GFAN);

            // Warning for undefined market names.
            if (!supportedMarketNames.contains(marketName)) {
                Log.w(TAPJOY_CONNECT, "Warning -- undefined ALTERNATE_MARKET: " + marketName);
            }
        }

        // Get the referral URL
        String tempReferralURL = settings.getString(TapjoyConstants.PREF_REFERRAL_URL, null);
        if (tempReferralURL != null && !tempReferralURL.equals(""))
            referralURL = tempReferralURL;

        // Get the client package name.
        clientPackage = context.getPackageName();

        TapjoyLog.i(TAPJOY_CONNECT, "Metadata successfully loaded");

        TapjoyLog.i(TAPJOY_CONNECT, "APP_ID = [" + appID + "]");
        TapjoyLog.i(TAPJOY_CONNECT, "ANDROID_ID: [" + androidID + "]");
        TapjoyLog.i(TAPJOY_CONNECT, "CLIENT_PACKAGE = [" + clientPackage + "]");

        TapjoyLog.i(TAPJOY_CONNECT, "deviceID: [" + deviceID + "]");
        TapjoyLog.i(TAPJOY_CONNECT, "sha2DeviceID: [" + sha2DeviceID + "]");
        TapjoyLog.i(TAPJOY_CONNECT, "" + TapjoyConstants.TJC_DEVICE_SERIAL_ID + ": [" + serialID + "]");
        TapjoyLog.i(TAPJOY_CONNECT, "" + TapjoyConstants.TJC_DEVICE_MAC_ADDRESS + ": [" + macAddress + "]");
        TapjoyLog.i(TAPJOY_CONNECT,
                "" + TapjoyConstants.TJC_DEVICE_SHA1_MAC_ADDRESS + ": [" + sha1MacAddress + "]");

        TapjoyLog.i(TAPJOY_CONNECT, "deviceName: [" + deviceModel + "]");
        TapjoyLog.i(TAPJOY_CONNECT, "deviceManufacturer: [" + deviceManufacturer + "]");
        TapjoyLog.i(TAPJOY_CONNECT, "deviceType: [" + deviceType + "]");
        TapjoyLog.i(TAPJOY_CONNECT, "libraryVersion: [" + libraryVersion + "]");
        TapjoyLog.i(TAPJOY_CONNECT, "deviceOSVersion: [" + deviceOSVersion + "]");

        TapjoyLog.i(TAPJOY_CONNECT, "COUNTRY_CODE: [" + deviceCountryCode + "]");
        TapjoyLog.i(TAPJOY_CONNECT, "LANGUAGE_CODE: [" + deviceLanguage + "]");

        TapjoyLog.i(TAPJOY_CONNECT, "density: [" + deviceScreenDensity + "]");
        TapjoyLog.i(TAPJOY_CONNECT, "screen_layout: [" + deviceScreenLayoutSize + "]");

        TapjoyLog.i(TAPJOY_CONNECT, "carrier_name: [" + carrierName + "]");
        TapjoyLog.i(TAPJOY_CONNECT, "carrier_country_code: [" + carrierCountryCode + "]");
        TapjoyLog.i(TAPJOY_CONNECT,
                "" + TapjoyConstants.TJC_MOBILE_COUNTRY_CODE + ": [" + mobileCountryCode + "]");
        TapjoyLog.i(TAPJOY_CONNECT,
                "" + TapjoyConstants.TJC_MOBILE_NETWORK_CODE + ": [" + mobileNetworkCode + "]");
        TapjoyLog.i(TAPJOY_CONNECT, "" + TapjoyConstants.TJC_MARKET_NAME + ": [" + marketName + "]");

        TapjoyLog.i(TAPJOY_CONNECT, "referralURL: [" + referralURL + "]");

        if (connectFlags != null) {
            TapjoyLog.i(TAPJOY_CONNECT, "Connect Flags:");
            TapjoyLog.i(TAPJOY_CONNECT, "--------------------");

            Set<Entry<String, String>> entries = connectFlags.entrySet();
            Iterator<Entry<String, String>> iterator = entries.iterator();

            while (iterator.hasNext()) {
                Entry<String, String> item = iterator.next();
                TapjoyLog.i(TAPJOY_CONNECT,
                        "key: " + item.getKey() + ", value: " + Uri.encode(item.getValue()));
            }
        }
    } catch (Exception e) {
        TapjoyLog.e(TAPJOY_CONNECT, "Error initializing Tapjoy parameters.  e=" + e.toString());
    }
}

From source file:org.hfoss.posit.android.sync.Communicator.java

/**
 * Registers a new expedition with the server.
 * @param projectId  Posit's current project id.
 * @return Returns the expedition number received from the server or -1 if something
 * goes wrong./*from   w  ww  .  j a  v a  2 s. com*/
 */
public int registerExpeditionId(Context context, int projectId) {
    mContext = context;

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String server = prefs.getString(SERVER_PREF, "");

    TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    String imei = telephonyManager.getDeviceId();

    HashMap<String, String> sendMap = new HashMap<String, String>();
    addRemoteIdentificationInfo(sendMap);
    String addExpeditionUrl = server + "/api/addExpedition?authKey=" + getAuthKey(context);
    sendMap.put("projectId", "" + projectId);
    Log.i(TAG, "URL=" + addExpeditionUrl + " projectId = " + projectId);
    String response = doHTTPPost(addExpeditionUrl, sendMap);
    Log.d(TAG, "registerExpeditionId response = " + response);

    // The server should return an expedition number if everything goes ok.  If 
    //  an error occurs, it will return an error message that cannot parse to an int
    //  which will cause an exception here.
    try {
        Integer i = Integer.parseInt(response);
        return i;
    } catch (NumberFormatException e) {
        Log.e(TAG, "Communicator, registerExpeditionId, Invalid response received");
        return -1;
    }
}