Example usage for android.content.pm PackageManager getPackageInfo

List of usage examples for android.content.pm PackageManager getPackageInfo

Introduction

In this page you can find the example usage for android.content.pm PackageManager getPackageInfo.

Prototype

public abstract PackageInfo getPackageInfo(VersionedPackage versionedPackage, @PackageInfoFlags int flags)
        throws NameNotFoundException;

Source Link

Document

Retrieve overall information about an application package that is installed on the system.

Usage

From source file:com.apptentive.android.sdk.ApptentiveInternal.java

public boolean init() {
    boolean bRet = true;
    codePointStore.init();// ww w .  j  a v  a  2 s .c om
    /* If Message Center feature has never been used before, don't initialize message polling thread.
     * Message Center feature will be seen as used, if one of the following conditions has been met:
     * 1. Message Center has been opened for the first time
     * 2. The first Push is received which would open Message Center
     * 3. An unreadMessageCountListener() is set up
     */
    boolean featureEverUsed = prefs.getBoolean(Constants.PREF_KEY_MESSAGE_CENTER_FEATURE_USED, false);
    if (featureEverUsed) {
        messageManager.init();
    }
    conversationToken = prefs.getString(Constants.PREF_KEY_CONVERSATION_TOKEN, null);
    conversationId = prefs.getString(Constants.PREF_KEY_CONVERSATION_ID, null);
    personId = prefs.getString(Constants.PREF_KEY_PERSON_ID, null);
    apptentiveToolbarTheme = appContext.getResources().newTheme();

    boolean apptentiveDebug = false;
    String logLevelOverride = null;
    String manifestApiKey = null;
    try {
        appPackageName = appContext.getPackageName();
        PackageManager packageManager = appContext.getPackageManager();
        PackageInfo packageInfo = packageManager.getPackageInfo(appPackageName,
                PackageManager.GET_META_DATA | PackageManager.GET_RECEIVERS);
        ApplicationInfo ai = packageInfo.applicationInfo;

        Bundle metaData = ai.metaData;
        if (metaData != null) {
            manifestApiKey = Util.trim(metaData.getString(Constants.MANIFEST_KEY_APPTENTIVE_API_KEY));
            logLevelOverride = Util.trim(metaData.getString(Constants.MANIFEST_KEY_APPTENTIVE_LOG_LEVEL));
            apptentiveDebug = metaData.getBoolean(Constants.MANIFEST_KEY_APPTENTIVE_DEBUG);
        }

        // Used for application theme inheritance if the theme is an AppCompat theme.
        setApplicationDefaultTheme(ai.theme);

        AppRelease appRelease = AppRelease.generateCurrentAppRelease(appContext);

        isAppDebuggable = appRelease.getDebug();
        currentVersionCode = appRelease.getVersionCode();
        currentVersionName = appRelease.getVersionName();

        VersionHistoryEntry lastVersionEntrySeen = VersionHistoryStore.getLastVersionSeen();

        if (lastVersionEntrySeen == null) {
            onVersionChanged(null, currentVersionCode, null, currentVersionName, appRelease);
        } else {
            int lastSeenVersionCode = lastVersionEntrySeen.getVersionCode();
            Apptentive.Version lastSeenVersionNameVersion = new Apptentive.Version();
            lastSeenVersionNameVersion.setVersion(lastVersionEntrySeen.getVersionName());
            if (!(currentVersionCode == lastSeenVersionCode)
                    || !currentVersionName.equals(lastSeenVersionNameVersion.getVersion())) {
                onVersionChanged(lastVersionEntrySeen.getVersionCode(), currentVersionCode,
                        lastVersionEntrySeen.getVersionName(), currentVersionName, appRelease);
            }
        }
        defaultAppDisplayName = packageManager
                .getApplicationLabel(packageManager.getApplicationInfo(packageInfo.packageName, 0)).toString();

        // Prevent delayed run-time exception if the app upgrades from pre-2.0 and doesn't remove NetworkStateReceiver from manifest
        ActivityInfo[] registered = packageInfo.receivers;
        if (registered != null) {
            for (ActivityInfo activityInfo : registered) {
                // Throw assertion error when relict class found in manifest.
                if (activityInfo.name.equals("com.apptentive.android.sdk.comm.NetworkStateReceiver")) {
                    throw new AssertionError(
                            "NetworkStateReceiver has been removed from Apptentive SDK, please make sure it's also removed from manifest file");
                }
            }
        }

    } catch (Exception e) {
        ApptentiveLog.e("Unexpected error while reading application or package info.", e);
        bRet = false;
    }

    // Set debuggable and appropriate log level.
    if (apptentiveDebug) {
        ApptentiveLog.i("Apptentive debug logging set to VERBOSE.");
        setMinimumLogLevel(ApptentiveLog.Level.VERBOSE);
    } else if (logLevelOverride != null) {
        ApptentiveLog.i("Overriding log level: %s", logLevelOverride);
        setMinimumLogLevel(ApptentiveLog.Level.parse(logLevelOverride));
    } else {
        if (isAppDebuggable) {
            setMinimumLogLevel(ApptentiveLog.Level.VERBOSE);
        }
    }
    ApptentiveLog.i("Debug mode enabled? %b", isAppDebuggable);

    String lastSeenSdkVersion = prefs.getString(Constants.PREF_KEY_LAST_SEEN_SDK_VERSION, "");
    if (!lastSeenSdkVersion.equals(Constants.APPTENTIVE_SDK_VERSION)) {
        onSdkVersionChanged(appContext, lastSeenSdkVersion, Constants.APPTENTIVE_SDK_VERSION);
    }

    // The apiKey can be passed in programmatically, or we can fallback to checking in the manifest.
    if (TextUtils.isEmpty(apiKey) && !TextUtils.isEmpty(manifestApiKey)) {
        apiKey = manifestApiKey;
    }
    if (TextUtils.isEmpty(apiKey) || apiKey.contains(Constants.EXAMPLE_API_KEY_VALUE)) {
        String errorMessage = "The Apptentive API Key is not defined. You may provide your Apptentive API Key in Apptentive.register(), or in as meta-data in your AndroidManifest.xml.\n"
                + "<meta-data android:name=\"apptentive_api_key\"\n"
                + "           android:value=\"@string/your_apptentive_api_key\"/>";
        if (isAppDebuggable) {
            throw new RuntimeException(errorMessage);
        } else {
            ApptentiveLog.e(errorMessage);
        }
    } else {
        ApptentiveLog.d("Using cached Apptentive API Key");
    }
    ApptentiveLog.d("Apptentive API Key: %s", apiKey);

    // Grab app info we need to access later on.
    androidId = Settings.Secure.getString(appContext.getContentResolver(),
            android.provider.Settings.Secure.ANDROID_ID);
    ApptentiveLog.d("Android ID: ", androidId);
    ApptentiveLog.d("Default Locale: %s", Locale.getDefault().toString());
    ApptentiveLog.d("Conversation id: %s", prefs.getString(Constants.PREF_KEY_CONVERSATION_ID, "null"));
    return bRet;
}

From source file:de.tudarmstadt.dvs.myhealthassistant.myhealthhub.services.messagehandler.MessageHandler.java

/**
 * Verifies if the package is installed using the PackageManager and the given package name
 * @param packageName//from   w w  w . ja  v a 2  s.c om
 * @return Returns true if package is installed
 */
public boolean isPackageInstalled(String packageName) {
    if (packageName == null)
        return false;
    PackageManager pm = getPackageManager();
    try {
        PackageInfo info = pm.getPackageInfo(packageName, PackageManager.GET_META_DATA);
    } catch (NameNotFoundException e) {
        return false;
    }
    return true;
}

From source file:com.irccloud.android.activity.LoginActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT >= 21) {
        Bitmap cloud = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        setTaskDescription(new ActivityManager.TaskDescription(getResources().getString(R.string.app_name),
                cloud, 0xff0b2e60));//from  ww  w  .j  ava2  s.  c o m
        cloud.recycle();
    }

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    setContentView(R.layout.activity_login);

    loading = findViewById(R.id.loading);

    connecting = findViewById(R.id.connecting);
    connectingMsg = (TextView) findViewById(R.id.connectingMsg);
    progressBar = (ProgressBar) findViewById(R.id.connectingProgress);

    loginHint = (LinearLayout) findViewById(R.id.loginHint);
    signupHint = (LinearLayout) findViewById(R.id.signupHint);
    hostHint = (TextView) findViewById(R.id.hostHint);

    login = findViewById(R.id.login);
    name = (EditText) findViewById(R.id.name);
    if (savedInstanceState != null && savedInstanceState.containsKey("name"))
        name.setText(savedInstanceState.getString("name"));
    email = (AutoCompleteTextView) findViewById(R.id.email);
    if (BuildConfig.ENTERPRISE)
        email.setHint(R.string.email_enterprise);
    ArrayList<String> accounts = new ArrayList<String>();
    AccountManager am = (AccountManager) getSystemService(Context.ACCOUNT_SERVICE);
    for (Account a : am.getAccounts()) {
        if (a.name.contains("@") && !accounts.contains(a.name))
            accounts.add(a.name);
    }
    if (accounts.size() > 0)
        email.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
                accounts.toArray(new String[accounts.size()])));

    if (savedInstanceState != null && savedInstanceState.containsKey("email"))
        email.setText(savedInstanceState.getString("email"));

    password = (EditText) findViewById(R.id.password);
    password.setOnEditorActionListener(new OnEditorActionListener() {
        public boolean onEditorAction(TextView exampleView, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                new LoginTask().execute((Void) null);
                return true;
            }
            return false;
        }
    });
    if (savedInstanceState != null && savedInstanceState.containsKey("password"))
        password.setText(savedInstanceState.getString("password"));

    host = (EditText) findViewById(R.id.host);
    if (BuildConfig.ENTERPRISE)
        host.setText(NetworkConnection.IRCCLOUD_HOST);
    else
        host.setVisibility(View.GONE);
    host.setOnEditorActionListener(new OnEditorActionListener() {
        public boolean onEditorAction(TextView exampleView, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                new LoginTask().execute((Void) null);
                return true;
            }
            return false;
        }
    });
    if (savedInstanceState != null && savedInstanceState.containsKey("host"))
        host.setText(savedInstanceState.getString("host"));
    else
        host.setText(getSharedPreferences("prefs", 0).getString("host", BuildConfig.HOST));

    if (host.getText().toString().equals("api.irccloud.com")
            || host.getText().toString().equals("www.irccloud.com"))
        host.setText("");

    loginBtn = (Button) findViewById(R.id.loginBtn);
    loginBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            new LoginTask().execute((Void) null);
        }
    });
    loginBtn.setFocusable(true);
    loginBtn.requestFocus();

    sendAccessLinkBtn = (Button) findViewById(R.id.sendAccessLink);
    sendAccessLinkBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            new ResetPasswordTask().execute((Void) null);
        }
    });

    nextBtn = (Button) findViewById(R.id.nextBtn);
    nextBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            if (host.getText().length() > 0) {
                NetworkConnection.IRCCLOUD_HOST = host.getText().toString();
                trimHost();

                new EnterpriseConfigTask().execute((Void) null);
            }
        }
    });

    TOS = (TextView) findViewById(R.id.TOS);
    TOS.setMovementMethod(new LinkMovementMethod());

    forgotPassword = (TextView) findViewById(R.id.forgotPassword);
    forgotPassword.setOnClickListener(forgotPasswordClickListener);

    enterpriseLearnMore = (TextView) findViewById(R.id.enterpriseLearnMore);
    enterpriseLearnMore.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            if (isPackageInstalled("com.irccloud.android", LoginActivity.this)) {
                startActivity(getPackageManager().getLaunchIntentForPackage("com.irccloud.android"));
            } else {
                try {
                    startActivity(new Intent(Intent.ACTION_VIEW,
                            Uri.parse("market://details?id=com.irccloud.android")));
                } catch (Exception e) {
                    startActivity(new Intent(Intent.ACTION_VIEW,
                            Uri.parse("http://play.google.com/store/apps/details?id=com.irccloud.android")));
                }
            }
        }

        private boolean isPackageInstalled(String packagename, Context context) {
            PackageManager pm = context.getPackageManager();
            try {
                pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES);
                return true;
            } catch (NameNotFoundException e) {
                return false;
            }
        }
    });
    enterpriseHint = (LinearLayout) findViewById(R.id.enterpriseHint);

    EnterYourEmail = (TextView) findViewById(R.id.enterYourEmail);

    signupHint.setOnClickListener(signupHintClickListener);
    loginHint.setOnClickListener(loginHintClickListener);

    signupBtn = (Button) findViewById(R.id.signupBtn);
    signupBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            new LoginTask().execute((Void) null);
        }
    });

    TextView version = (TextView) findViewById(R.id.version);
    try {
        version.setText("Version " + getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
    } catch (NameNotFoundException e) {
        version.setVisibility(View.GONE);
    }

    Typeface LatoRegular = Typeface.createFromAsset(getAssets(), "Lato-Regular.ttf");
    Typeface LatoLightItalic = Typeface.createFromAsset(getAssets(), "Lato-LightItalic.ttf");

    for (int i = 0; i < signupHint.getChildCount(); i++) {
        View v = signupHint.getChildAt(i);
        if (v instanceof TextView) {
            ((TextView) v).setTypeface(LatoRegular);
        }
    }

    for (int i = 0; i < loginHint.getChildCount(); i++) {
        View v = loginHint.getChildAt(i);
        if (v instanceof TextView) {
            ((TextView) v).setTypeface(LatoRegular);
        }
    }

    LinearLayout IRCCloud = (LinearLayout) findViewById(R.id.IRCCloud);
    for (int i = 0; i < IRCCloud.getChildCount(); i++) {
        View v = IRCCloud.getChildAt(i);
        if (v instanceof TextView) {
            ((TextView) v).setTypeface(LatoRegular);
        }
    }

    notAProblem = (LinearLayout) findViewById(R.id.notAProblem);
    for (int i = 0; i < notAProblem.getChildCount(); i++) {
        View v = notAProblem.getChildAt(i);
        if (v instanceof TextView) {
            ((TextView) v).setTypeface((i == 0) ? LatoRegular : LatoLightItalic);
        }
    }

    loginSignupHint = (LinearLayout) findViewById(R.id.loginSignupHint);
    for (int i = 0; i < loginSignupHint.getChildCount(); i++) {
        View v = loginSignupHint.getChildAt(i);
        if (v instanceof TextView) {
            ((TextView) v).setTypeface(LatoRegular);
            ((TextView) v).setOnClickListener((i == 0) ? loginHintClickListener : signupHintClickListener);
        }
    }

    name.setTypeface(LatoRegular);
    email.setTypeface(LatoRegular);
    password.setTypeface(LatoRegular);
    host.setTypeface(LatoRegular);
    loginBtn.setTypeface(LatoRegular);
    signupBtn.setTypeface(LatoRegular);
    TOS.setTypeface(LatoRegular);
    EnterYourEmail.setTypeface(LatoRegular);
    hostHint.setTypeface(LatoLightItalic);

    if (BuildConfig.ENTERPRISE) {
        name.setVisibility(View.GONE);
        email.setVisibility(View.GONE);
        password.setVisibility(View.GONE);
        loginBtn.setVisibility(View.GONE);
        signupBtn.setVisibility(View.GONE);
        TOS.setVisibility(View.GONE);
        signupHint.setVisibility(View.GONE);
        loginHint.setVisibility(View.GONE);
        forgotPassword.setVisibility(View.GONE);
        loginSignupHint.setVisibility(View.GONE);
        EnterYourEmail.setVisibility(View.GONE);
        sendAccessLinkBtn.setVisibility(View.GONE);
        notAProblem.setVisibility(View.GONE);
        enterpriseLearnMore.setVisibility(View.VISIBLE);
        enterpriseHint.setVisibility(View.VISIBLE);
        host.setVisibility(View.VISIBLE);
        nextBtn.setVisibility(View.VISIBLE);
        hostHint.setVisibility(View.VISIBLE);
        host.requestFocus();
    }

    if (savedInstanceState != null && savedInstanceState.containsKey("signup")
            && savedInstanceState.getBoolean("signup")) {
        signupHintClickListener.onClick(null);
    }

    if (savedInstanceState != null && savedInstanceState.containsKey("login")
            && savedInstanceState.getBoolean("login")) {
        loginHintClickListener.onClick(null);
    }

    if (savedInstanceState != null && savedInstanceState.containsKey("forgotPassword")
            && savedInstanceState.getBoolean("forgotPassword")) {
        forgotPasswordClickListener.onClick(null);
    }

    mResolvingError = savedInstanceState != null && savedInstanceState.getBoolean("resolving_error", false);

    mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(Auth.CREDENTIALS_API)
            .addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
}

From source file:com.kjsaw.alcosys.ibacapp.IBAC.java

private void showAppVersion() {
    try {/*from www .  ja  v  a2s  . co  m*/
        PackageManager manager = this.getPackageManager();
        Resources resource = this.getResources();
        String versionLabel = resource.getString(R.string.app_version_label) + " ";
        PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
        String versionNumber = info.versionName;
        textViewAppVersion.setText(versionLabel + versionNumber);
    } catch (NameNotFoundException e) {
        Logging.d("AppVersionNotFound: " + e.getMessage());
    }
}

From source file:com.southernstorm.tvguide.TvChannelCache.java

@Override
public void addContext(Context context) {
    super.addContext(context);
    if (region == null) {
        // Load the region from the settings for the first time.
        SharedPreferences prefs = context.getSharedPreferences("TVGuideActivity", 0);
        region = prefs.getString("region", "");
        if (region != null && region.equals(""))
            region = null;/*from  w w  w .j a  v a  2 s  .  c o m*/
    }

    // Determine if the application was built as debug or release to set the debug flag.
    if (!debugLoaded) {
        debugLoaded = true;
        debug = false;
        PackageManager manager = context.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            if ((info.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0)
                debug = true;
        } catch (NameNotFoundException e) {
        }
    }

    // Load the channels.
    if (channels.size() == 0 && region != null)
        loadChannels();
}

From source file:com.linkbubble.Settings.java

private boolean doesPackageExist(PackageManager pm, String targetPackage) {
    try {/* w w  w . j  a  va2s. c  o m*/
        PackageInfo info = pm.getPackageInfo(targetPackage, PackageManager.GET_META_DATA);
    } catch (PackageManager.NameNotFoundException e) {
        return false;
    }
    return true;
}

From source file:dev.ukanth.ufirewall.Api.java

public static boolean isPackageExists(PackageManager pm, String targetPackage) {
    try {/*  www.j ava 2s .  c om*/
        pm.getPackageInfo(targetPackage, PackageManager.GET_META_DATA);
    } catch (NameNotFoundException e) {
        return false;
    }
    return true;
}

From source file:com.onesignal.OneSignal.java

private static void registerUser() {
    Log(LOG_LEVEL.DEBUG,/*  www.ja v a 2  s. c om*/
            "registerUser: registerForPushFired:" + registerForPushFired + ", locationFired: " + locationFired);

    if (!registerForPushFired || !locationFired)
        return;

    if (ranSessionInitThread) {
        updateRegistrationId();
        return;
    }

    ranSessionInitThread = true;

    new Thread(new Runnable() {
        public void run() {
            OneSignalStateSynchronizer.UserState userState = OneSignalStateSynchronizer.getNewUserState();

            String packageName = appContext.getPackageName();
            PackageManager packageManager = appContext.getPackageManager();

            userState.set("app_id", appId);
            userState.set("identifier", lastRegistrationId);

            String adId = mainAdIdProvider.getIdentifier(appContext);
            // "... must use the advertising ID (when available on a device) in lieu of any other device identifiers ..."
            // https://play.google.com/about/developer-content-policy.html
            if (adId == null)
                adId = new AdvertisingIdProviderFallback().getIdentifier(appContext);
            userState.set("ad_id", adId);
            userState.set("device_os", Build.VERSION.RELEASE);
            userState.set("timezone", getTimeZoneOffset());
            userState.set("language", Locale.getDefault().getLanguage());
            userState.set("sdk", VERSION);
            userState.set("sdk_type", sdkType);
            userState.set("android_package", packageName);
            userState.set("device_model", Build.MODEL);
            userState.set("device_type", deviceType);
            userState.setState("subscribableStatus", subscribableStatus);

            try {
                userState.set("game_version", packageManager.getPackageInfo(packageName, 0).versionCode);
            } catch (PackageManager.NameNotFoundException e) {
            }

            List<PackageInfo> packList = packageManager.getInstalledPackages(0);
            int count = -1;
            for (int i = 0; i < packList.size(); i++)
                count += ((packList.get(i).applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) ? 1 : 0;
            userState.set("pkgc", count);
            userState.set("net_type", osUtils.getNetType());
            userState.set("carrier", osUtils.getCarrierName());
            userState.set("rooted", RootToolsInternalMethods.isRooted());

            userState.set("lat", lastLocLat);
            userState.set("long", lastLocLong);
            userState.set("loc_acc", lastLocAcc);
            userState.set("loc_type", lastLocType);

            OneSignalStateSynchronizer.postSession(userState);
        }
    }).start();
}

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. 
 *///w w  w .  j a v a 2  s . 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());
    }
}