Example usage for android.telephony TelephonyManager getLine1Number

List of usage examples for android.telephony TelephonyManager getLine1Number

Introduction

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

Prototype

@SuppressAutoDoc 
@RequiresPermission(anyOf = { android.Manifest.permission.READ_PHONE_STATE,
        android.Manifest.permission.READ_SMS, android.Manifest.permission.READ_PHONE_NUMBERS })
public String getLine1Number() 

Source Link

Document

Returns the phone number string for line 1, for example, the MSISDN for a GSM phone.

Usage

From source file:com.mibr.android.intelligentreminder.INeedToo.java

private String getDeviceId() {
    TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    return tm.getLine1Number();
}

From source file:com.lewa.crazychapter11.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    //set to full screen
    // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,  WindowManager.LayoutParams.FLAG_FULLSCREEN);

    ///set to no title
    // requestWindowFeature(Window.FEATURE_NO_TITLE);
    // acionBar = getSupportActionBar();
    // acionBar = getActionBar();
    // acionBar.hide();

    // Window win = getWindow();
    //          win.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    //          win.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS  | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);  
    //          win.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);  
    // win.setStatusBarColor(Color.TRANSPARENT);  
    // win.setNavigationBarColor(Color.TRANSPARENT);

    /*//*w  w  w  .j a  v a2  s  . c o  m*/
       win.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
       win.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS  | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);  
       win.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN  | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION  | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);  
       win.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);  
       win.setStatusBarColor(Color.TRANSPARENT);  
       win.setNavigationBarColor(Color.TRANSPARENT);
    //*/

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    /* setTheme(R.style.CrazyTheme); */
    AddGameBtn();
    AddNoification();
    LookupContact();
    AddServiceBtn();
    broadcastMain();
    mediaPlayerMain();
    mediaRecordSoundMain();
    cameraMain();
    recordvideoMain();
    queMySql();
    TestFragment();
    justForTest();
    LoadJson();
    AddTestBtn();
    AddUsageStatsBtn();
    AddPeopleProvideBtn();
    getInput();

    ////just for test shutdown broadcast receiver
    IntentFilter mIntentFilter = new IntentFilter("android.intent.action.ACTION_SHUTDOWN");
    mIntentFilter.addAction("com.lewa.alarm.test");
    mIntentFilter.addAction("android.provider.Telephony.SECRET_CODE");
    mIntentFilter.addAction("android.intent.action.SCREEN_ON");
    mIntentFilter.addAction("android.intent.action.SCREEN_OFF");
    mShoutdown = new shutdownReceiver();
    registerReceiver(mShoutdown, mIntentFilter);
    ////test      

    preferences = getSharedPreferences("crazyit", MODE_WORLD_WRITEABLE | MODE_WORLD_READABLE);
    editor = preferences.edit();

    preferencestime = getSharedPreferences("RMS_Shutdown_time", MODE_WORLD_WRITEABLE | MODE_WORLD_READABLE);
    editortime = preferencestime.edit();

    SharedShutdownTimeRead();

    AddSharedPreBtn();

    etNum = (EditText) findViewById(R.id.etNum);

    // //
    int maxLength = 4;

    InputFilter[] fArray = new InputFilter[1];

    fArray[0] = new InputFilter.LengthFilter(maxLength);

    etNum.setFilters(fArray);
    // //

    calThread = new CalThread();
    calThread.start();

    Log.i("algerheMain", "MainActivity onCreate in!!");
    String page = getString(R.string.str_page, "345", "24");
    Log.i("algerheMain", "page=" + page);

    // /just for test here
    ComponentName comp = getIntent().getComponent();
    show_txt = (EditText) findViewById(R.id.show_txt);
    show_txt.setText(
            "??" + comp.getPackageName() + " \n ??" + comp.getClassName());

    ////MD5 check item
    ///1.IMEI
    TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    String szImei = TelephonyMgr.getDeviceId();
    String m_szSIMSerialNm = TelephonyMgr.getSimSerialNumber();
    CellLocation m_location = TelephonyMgr.getCellLocation();
    String m_Line1Number = TelephonyMgr.getLine1Number();
    String m_OperatorName = TelephonyMgr.getSimOperatorName();
    Log.i("algerheTelephonyMgr", "szImei=" + szImei);
    Log.i("algerheTelephonyMgr", "m_szSIMSerialNm=" + m_szSIMSerialNm);
    Log.i("algerheTelephonyMgr", "m_location=" + m_location);
    Log.i("algerheTelephonyMgr", "m_Line1Number=" + m_Line1Number);
    Log.i("algerheTelephonyMgr", "m_OperatorName=" + m_OperatorName);

    Log.i("algerheMain01", "szImei=" + szImei);
    Log.i("algerheMain01", "m_szSIMSerialNm=" + m_szSIMSerialNm);

    ///2.Pseudo-Unique ID
    String m_szDevIDShort = "35" + //we make this look like a valid IMEI 
            Build.BOARD.length() % 10 + Build.BRAND.length() % 10 + Build.CPU_ABI.length() % 10
            + Build.DEVICE.length() % 10 + Build.DISPLAY.length() % 10 + Build.HOST.length() % 10
            + Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 + Build.MODEL.length() % 10
            + Build.PRODUCT.length() % 10 + Build.TAGS.length() % 10 + Build.TYPE.length() % 10
            + Build.USER.length() % 10; //13 digits

    Log.i("algerheMain01", "m_szDevIDShort=" + m_szDevIDShort);

    ///3. Android ID
    String m_szAndroidID = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
    Log.i("algerheMain01", "m_szAndroidID=" + m_szAndroidID);

    ///4.WLAN MAC Address string
    WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    String m_szWLANMAC = "unknow_wifi_mac";
    if (wm != null && wm.getConnectionInfo() != null) {
        m_szWLANMAC = wm.getConnectionInfo().getMacAddress();
    }

    Log.i("algerheMain01", "m_szWLANMAC=" + m_szWLANMAC);

    ///5.BT MAC Address string
    BluetoothAdapter m_BluetoothAdapter = null; // Local Bluetooth adapter      
    m_BluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    String m_szBTMAC = m_BluetoothAdapter.getAddress();

    Log.i("algerheMain01", "m_szBTMAC=" + m_szBTMAC);

    ///6.sim serial number .getSimSerialNumber()

    // /

    ///reflect test   
    checkMethod();

    // */
    final Intent alarmIntent = new Intent();
    Log.i("algerheMain00", "isLewaRom=" + isLewaRom(this, alarmIntent));

    handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x4567) {
                String languageStr = null;
                String countryStr = null;

                Locale[] locList = Locale.getAvailableLocales();

                for (int i = 0; i < locList.length; i++) {
                    languageStr += locList[i].getLanguage();
                    countryStr += locList[i].getCountry();
                }
                // show_txt = (EditText) findViewById(R.id.show_txt);
                show_txt.setText("" + languageStr + " \n " + countryStr);
            } else if (msg.what == 0x2789) {
                Log.i("algerheAlarm", "send alarm message in time=" + System.currentTimeMillis() + "\n action="
                        + alarmIntent.getAction());

                // sendBroadcast(alarmIntent);
            }
        }
    };

    // String strApkPath = intent.getStringExtra("apkPath");
    //         String strCmd = "pm install -r " + strApkPath;
    //         try {
    //             Process install = Runtime.getRuntime().exec(strCmd);
    //             Log.d(TAG, "install = " + install + ", strCmd =" + strCmd);
    //         }catch (Exception ex){
    //             Log.d(TAG, ex.getMessage());
    //         }   
    // */
}

From source file:com.t2.compassionMeditation.Graphs1Activity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.i(TAG, this.getClass().getSimpleName() + ".onCreate()");

    // We don't want the screen to timeout in this activity
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

    this.requestWindowFeature(Window.FEATURE_NO_TITLE); // This needs to happen BEFORE setContentView
    setContentView(R.layout.graphs_activity_layout);
    mInstance = this;

    sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    mLoggingEnabled = SharedPref.getBoolean(this, "enable_logging", true);
    mDatabaseEnabled = SharedPref.getBoolean(this, "database_enabled", false);
    mAntHrmEnabled = SharedPref.getBoolean(this, "enable_ant_hrm", false);

    mInternalSensorMonitoring = SharedPref.getBoolean(this, "inernal_sensor_monitoring_enabled", false);

    if (mAntHrmEnabled) {
        mHeartRateSource = HEARTRATE_ANT;
    } else {/*w  w w.ja v a 2 s .  c  o m*/
        mHeartRateSource = HEARTRATE_ZEPHYR;
    }

    // The session start time will be used as session id
    // Note this also sets session start time
    // **** This session ID will be prepended to all JSON data stored
    //      in the external database until it's changed (by the start
    //      of a new session.
    Calendar cal = Calendar.getInstance();
    SharedPref.setBioSessionId(sharedPref, cal.getTimeInMillis());

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.US);
    String sessionDate = sdf.format(new Date());
    String userId = SharedPref.getString(this, "SelectedUser", "");
    long sessionId = SharedPref.getLong(this, "bio_session_start_time", 0);

    mDataOutHandler = new DataOutHandler(this, userId, sessionDate, mAppId,
            DataOutHandler.DATA_TYPE_EXTERNAL_SENSOR, sessionId);

    if (mDatabaseEnabled) {
        TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        String myNumber = telephonyManager.getLine1Number();

        String remoteDatabaseUri = SharedPref.getString(this, "database_sync_name",
                getString(R.string.database_uri));
        //            remoteDatabaseUri += myNumber; 

        Log.d(TAG, "Initializing database at " + remoteDatabaseUri); // TODO: remove
        try {
            mDataOutHandler.initializeDatabase(dDatabaseName, dDesignDocName, dDesignDocId, byDateViewName,
                    remoteDatabaseUri);
        } catch (DataOutHandlerException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
        }
        mDataOutHandler.setRequiresAuthentication(false);

    }

    mBioDataProcessor.initialize(mDataOutHandler);

    if (mLoggingEnabled) {
        mDataOutHandler.enableLogging(this);
    }

    if (mLogCatEnabled) {
        mDataOutHandler.enableLogCat();
    }

    // Log the version
    try {
        PackageManager packageManager = getPackageManager();
        PackageInfo info = packageManager.getPackageInfo(getPackageName(), 0);
        mApplicationVersion = info.versionName;
        String versionString = mAppId + " application version: " + mApplicationVersion;

        DataOutPacket packet = new DataOutPacket();
        packet.add(DataOutHandlerTags.version, versionString);
        try {
            mDataOutHandler.handleDataOut(packet);
        } catch (DataOutHandlerException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
        }

    } catch (NameNotFoundException e) {
        Log.e(TAG, e.toString());
    }

    // Set up UI elements
    Resources resources = this.getResources();
    AssetManager assetManager = resources.getAssets();

    mPauseButton = (Button) findViewById(R.id.buttonPause);
    mAddMeasureButton = (Button) findViewById(R.id.buttonAddMeasure);
    mTextInfoView = (TextView) findViewById(R.id.textViewInfo);
    mMeasuresDisplayText = (TextView) findViewById(R.id.measuresDisplayText);

    // Don't actually show skin conductance meter unless we get samples
    ImageView image = (ImageView) findViewById(R.id.imageView1);
    image.setImageResource(R.drawable.signal_bars0);

    // Check to see of there a device configured for EEG, if so then show the skin conductance meter
    String tmp = SharedPref.getString(this, "EEG", null);

    if (tmp != null) {
        image.setVisibility(View.VISIBLE);
    } else {
        image.setVisibility(View.INVISIBLE);
    }

    // Initialize SPINE by passing the fileName with the configuration properties
    try {
        mManager = SPINEFactory.createSPINEManager("SPINETestApp.properties", resources);
    } catch (InstantiationException e) {
        Log.e(TAG, "Exception creating SPINE manager: " + e.toString());
        e.printStackTrace();
    }

    try {
        currentMindsetData = new MindsetData(this);
    } catch (Exception e1) {
        Log.e(TAG, "Exception creating MindsetData: " + e1.toString());
        e1.printStackTrace();
    }

    // Establish nodes for BSPAN

    // Create a broadcast receiver. Note that this is used ONLY for command messages from the service
    // All data from the service goes through the mail SPINE mechanism (received(Data data)).
    // See public void received(Data data)
    this.mCommandReceiver = new SpineReceiver(this);

    int itemId = 0;
    eegPos = itemId; // eeg always comes first
    mBioParameters.clear();

    // First create GraphBioParameters for each of the EEG static params (ie mindset)
    for (itemId = 0; itemId < MindsetData.NUM_BANDS + 2; itemId++) { // 2 extra, for attention and meditation
        GraphBioParameter param = new GraphBioParameter(itemId, MindsetData.spectralNames[itemId], "", true);
        param.isShimmer = false;
        mBioParameters.add(param);
    }

    // Now create all of the potential dynamic GBraphBioParameters (GSR, EMG, ECG, EEG, HR, Skin Temp, Resp Rate
    //       String[] paramNamesStringArray = getResources().getStringArray(R.array.parameter_names);
    String[] paramNamesStringArray = getResources().getStringArray(R.array.parameter_names_less_eeg);

    for (String paramName : paramNamesStringArray) {
        if (paramName.equalsIgnoreCase("not assigned"))
            continue;

        GraphBioParameter param = new GraphBioParameter(itemId, paramName, "", true);

        if (paramName.equalsIgnoreCase("gsr")) {
            gsrPos = itemId;
            param.isShimmer = true;
            param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_GSR_SENSOR;
            param.shimmerNode = getShimmerNode();
        }

        if (paramName.equalsIgnoreCase("emg")) {
            emgPos = itemId;
            param.isShimmer = true;
            param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_EMG_SENSOR;
            param.shimmerNode = getShimmerNode();
        }

        if (paramName.equalsIgnoreCase("ecg")) {
            ecgPos = itemId;
            param.isShimmer = true;
            param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_ECG_SENSOR;
            param.shimmerNode = getShimmerNode();
        }

        if (paramName.equalsIgnoreCase("heart rate")) {
            heartRatePos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("resp rate")) {
            respRatePos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("skin temp")) {
            skinTempPos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth Airflow")) {
            eHealthAirFlowPos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth Temp")) {
            eHealthTempPos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth SpO2")) {
            eHealthSpO2Pos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth Heartrate")) {
            eHealthHeartRatePos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth GSR")) {
            eHealthGSRPos = itemId;
            param.isShimmer = false;
        }

        itemId++;
        mBioParameters.add(param);
    }

    // Since These are static nodes (Non-spine) we have to manually put them in the active node list
    Node mindsetNode = null;
    mindsetNode = new Node(new Address("" + Constants.RESERVED_ADDRESS_MINDSET)); // Note that the sensor id 0xfff1 (-15) is a reserved id for this particular sensor
    mManager.getActiveNodes().add(mindsetNode);

    Node zepherNode = null;
    zepherNode = new Node(new Address("" + Constants.RESERVED_ADDRESS_ZEPHYR));
    mManager.getActiveNodes().add(zepherNode);

    // The arduino node is programmed to look like a static Spine node
    // Note that currently we don't have  to turn it on or off - it's always streaming
    // Since Spine (in this case) is a static node we have to manually put it in the active node list
    // Since the 
    final int RESERVED_ADDRESS_ARDUINO_SPINE = 1; // 0x0001
    mSpineNode = new Node(new Address("" + RESERVED_ADDRESS_ARDUINO_SPINE));
    mManager.getActiveNodes().add(mSpineNode);

    final String sessionName;

    // Check to see if we were requested to play back a previous session
    try {
        Bundle bundle = getIntent().getExtras();

        if (bundle != null) {
            sessionName = bundle.getString(BioZenConstants.EXTRA_SESSION_NAME);

            AlertDialog.Builder alert = new AlertDialog.Builder(this);
            alert.setTitle("Replay Session " + sessionName + "?");
            alert.setMessage("Make sure to turn off all Bluetooth Sensors!");

            alert.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {

                    try {
                        mDataOutHandler.logNote("Replaying data from session " + sessionName);
                    } catch (DataOutHandlerException e) {
                        Log.e(TAG, e.toString());
                        e.printStackTrace();
                    }

                    replaySessionData(sessionName);
                    AlertDialog.Builder alert1 = new AlertDialog.Builder(mInstance);
                    alert1.setTitle("INFO");
                    alert1.setMessage("Replay of session complete!");
                    alert1.show();

                }
            });
            alert.show();
        }

    } catch (Exception e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
    }

    if (mInternalSensorMonitoring) {
        // IntentSender Launches our service scheduled with with the alarm manager 
        mBigBrotherService = PendingIntent.getService(Graphs1Activity.this, 0,
                new Intent(Graphs1Activity.this, BigBrotherService.class), 0);

        long firstTime = SystemClock.elapsedRealtime();
        // Schedule the alarm!
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, mPollingPeriod * 1000,
                mBigBrotherService);

        // Tell the user about what we did.
        Toast.makeText(Graphs1Activity.this, R.string.service_scheduled, Toast.LENGTH_LONG).show();

    }

    //testFIRFilter();

    //       testHR();

}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

/**
 * Gets the device number if is available.
 * //from   w w  w. j  a  va 2s. c  om
 * @param ctx
 * @return
 */
public static String device_getDeviceMobileNumber(Context ctx) {
    TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE);
    return tm.getLine1Number();
}

From source file:com.t2.compassionMeditation.MeditationActivity.java

/** Called when the activity is first created. */
@Override/*from   w  ww .j  av  a  2  s .c o m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.i(TAG, this.getClass().getSimpleName() + ".onCreate()");

    mInstance = this;
    mRateOfChange = new RateOfChange(mRateOfChangeSize);

    mIntroFade = 255;

    // We don't want the screen to timeout in this activity
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE); // This needs to happen BEFORE setContentView

    setContentView(R.layout.buddah_activity_layout);

    sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

    currentMindsetData = new MindsetData(this);
    mSaveRawWave = SharedPref.getBoolean(this, BioZenConstants.PREF_SAVE_RAW_WAVE,
            BioZenConstants.PREF_SAVE_RAW_WAVE_DEFAULT);

    mShowAGain = SharedPref.getBoolean(this, BioZenConstants.PREF_SHOW_A_GAIN,
            BioZenConstants.PREF_SHOW_A_GAIN_DEFAULT);

    mAllowComments = SharedPref.getBoolean(this, BioZenConstants.PREF_COMMENTS,
            BioZenConstants.PREF_COMMENTS_DEFAULT);

    mShowForeground = SharedPref.getBoolean(this, "show_lotus", true);
    mShowToast = SharedPref.getBoolean(this, "show_toast", true);

    mAudioTrackResourceName = SharedPref.getString(this, "audio_track", "None");
    mBaseImageResourceName = SharedPref.getString(this, "background_images", "Sunset");

    mBioHarnessParameters = getResources().getStringArray(R.array.bioharness_parameters_array);

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    String s = SharedPref.getString(this, BioZenConstants.PREF_SESSION_LENGTH, "10");
    mSecondsRemaining = Integer.parseInt(s) * 60;
    mSecondsTotal = mSecondsRemaining;

    s = SharedPref.getString(this, BioZenConstants.PREF_ALPHA_GAIN, "5");
    mAlphaGain = Float.parseFloat(s);

    mMovingAverage = new TMovingAverageFilter(mMovingAverageSize);
    mMovingAverageROC = new TMovingAverageFilter(mMovingAverageSizeROC);

    View v1 = findViewById(R.id.buddahView);
    v1.setOnTouchListener(this);

    Resources resources = this.getResources();
    AssetManager assetManager = resources.getAssets();

    // Set up member variables to UI Elements
    mTextInfoView = (TextView) findViewById(R.id.textViewInfo);
    mTextBioHarnessView = (TextView) findViewById(R.id.textViewBioHarness);
    mCountdownTextView = (TextView) findViewById(R.id.countdownTextView);
    mCountdownImageView = (ImageView) findViewById(R.id.imageViewCountdown);

    mPauseButton = (ImageButton) findViewById(R.id.buttonPause);
    mSignalImage = (ImageView) findViewById(R.id.imageView1);
    mTextViewInstructions = (TextView) findViewById(R.id.textViewInstructions);

    // Note that the seek bar is a debug thing - used only to set the
    // alpha of the buddah image manually for visual testing
    mSeekBar = (SeekBar) findViewById(R.id.seekBar1);
    mSeekBar.setOnSeekBarChangeListener(this);

    // Scale such that values to the right of center are scaled 1 - 10
    // and values to the left of center are scaled 0 = .99999
    if (mAlphaGain > 1.0) {
        mSeekBar.setProgress(50 + (int) (mAlphaGain * 5));
    } else {
        int i = (int) (mAlphaGain * 50);
        mSeekBar.setProgress(i);
    }
    //      mSeekBar.setProgress((int) mAlphaGain * 10);      

    // Controls start as invisible, need to touch screen to activate them
    mCountdownTextView.setVisibility(View.INVISIBLE);
    mCountdownImageView.setVisibility(View.INVISIBLE);
    mTextInfoView.setVisibility(View.INVISIBLE);
    mTextBioHarnessView.setVisibility(View.INVISIBLE);
    mPauseButton.setVisibility(View.INVISIBLE);
    mPauseButton.setVisibility(View.VISIBLE);
    mSeekBar.setVisibility(View.INVISIBLE);

    mBackgroundImage = (ImageView) findViewById(R.id.buddahView);
    mForegroundImage = (ImageView) findViewById(R.id.lotusView);
    mBaseImage = (ImageView) findViewById(R.id.backgroundView);

    if (!mShowForeground) {
        mForegroundImage.setVisibility(View.INVISIBLE);
    }

    int resource = 0;
    if (mBaseImageResourceName.equalsIgnoreCase("Buddah")) {
        mBackgroundImage.setImageResource(R.drawable.buddha);
        mForegroundImage.setImageResource(R.drawable.lotus_flower);
        mBaseImage.setImageResource(R.drawable.none_bg);
    } else if (mBaseImageResourceName.equalsIgnoreCase("Bob")) {
        mBackgroundImage.setImageResource(R.drawable.bigbob);
        mForegroundImage.setImageResource(R.drawable.red_nose);
        mBaseImage.setImageResource(R.drawable.none_bg);
    } else if (mBaseImageResourceName.equalsIgnoreCase("Sunset")) {
        mBackgroundImage.setImageResource(R.drawable.eeg_layer);
        mForegroundImage.setImageResource(R.drawable.breathing_rate);
        mBaseImage.setImageResource(R.drawable.meditation_bg);
    }

    // Initialize SPINE by passing the fileName with the configuration properties
    try {
        mManager = SPINEFactory.createSPINEManager("SPINETestApp.properties", resources);
    } catch (InstantiationException e) {
        Log.e(TAG, "Exception creating SPINE manager: " + e.toString());
        e.printStackTrace();
    }

    // Since Mindset is a static node we have to manually put it in the active node list
    // Note that the sensor id 0xfff1 (-15) is a reserved id for this particular sensor
    Node mindsetNode = null;
    mindsetNode = new Node(new Address("" + Constants.RESERVED_ADDRESS_MINDSET));
    mManager.getActiveNodes().add(mindsetNode);

    Node zepherNode = null;
    zepherNode = new Node(new Address("" + Constants.RESERVED_ADDRESS_ZEPHYR));
    mManager.getActiveNodes().add(zepherNode);

    // The arduino node is programmed to look like a static Spine node
    // Note that currently we don't have  to turn it on or off - it's always streaming
    // Since Spine (in this case) is a static node we have to manually put it in the active node list
    // Since the 
    final int RESERVED_ADDRESS_ARDUINO_SPINE = 1; // 0x0001
    mSpineNode = new Node(new Address("" + RESERVED_ADDRESS_ARDUINO_SPINE));
    mManager.getActiveNodes().add(mSpineNode);

    // Create a broadcast receiver. Note that this is used ONLY for command messages from the service
    // All data from the service goes through the mail SPINE mechanism (received(Data data)).
    // See public void received(Data data)
    this.mCommandReceiver = new SpineReceiver(this);

    try {
        PackageManager packageManager = this.getPackageManager();
        PackageInfo info = packageManager.getPackageInfo(this.getPackageName(), 0);
        mApplicationVersion = info.versionName;
        Log.i(TAG, "BioZen Application Version: " + mApplicationVersion + ", Activity Version: "
                + mActivityVersion);
    } catch (NameNotFoundException e) {
        Log.e(TAG, e.toString());
    }

    // First create GraphBioParameters for each of the ECG static params (ie mindset)      
    int itemId = 0;
    eegPos = itemId; // eeg always comes first
    mBioParameters.clear();

    for (itemId = 0; itemId < MindsetData.NUM_BANDS + 2; itemId++) { // 2 extra, for attention and meditation
        GraphBioParameter param = new GraphBioParameter(itemId, MindsetData.spectralNames[itemId], "", true);
        param.isShimmer = false;
        mBioParameters.add(param);
    }

    // Now create all of the potential dynamic GBraphBioParameters (GSR, EMG, ECG, HR, Skin Temp, Resp Rate
    String[] paramNamesStringArray = getResources().getStringArray(R.array.parameter_names);

    for (String paramName : paramNamesStringArray) {
        if (paramName.equalsIgnoreCase("not assigned"))
            continue;

        if (paramName.equalsIgnoreCase("EEG"))
            continue;

        GraphBioParameter param = new GraphBioParameter(itemId, paramName, "", true);

        if (paramName.equalsIgnoreCase("gsr")) {
            gsrPos = itemId;
            param.isShimmer = true;
            param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_GSR_SENSOR;
            param.shimmerNode = getShimmerNode();
        }

        if (paramName.equalsIgnoreCase("emg")) {
            emgPos = itemId;
            param.isShimmer = true;
            param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_EMG_SENSOR;
            param.shimmerNode = getShimmerNode();
        }

        if (paramName.equalsIgnoreCase("ecg")) {
            ecgPos = itemId;
            param.isShimmer = true;
            param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_ECG_SENSOR;
            param.shimmerNode = getShimmerNode();
        }

        if (paramName.equalsIgnoreCase("heart rate")) {
            heartRatePos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("resp rate")) {
            respRatePos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("skin temp")) {
            skinTempPos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth Airflow")) {
            eHealthAirFlowPos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth Temp")) {
            eHealthTempPos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth SpO2")) {
            eHealthSpO2Pos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth Heartrate")) {
            eHealthHeartRatePos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth GSR")) {
            eHealthGSRPos = itemId;
            param.isShimmer = false;
        }

        itemId++;
        mBioParameters.add(param);
    }

    // The session start time will be used as session id
    // Note this also sets session start time
    // **** This session ID will be prepended to all JSON data stored
    //      in the external database until it's changed (by the start
    //      of a new session.
    Calendar cal = Calendar.getInstance();
    SharedPref.setBioSessionId(sharedPref, cal.getTimeInMillis());

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.US);
    String sessionDate = sdf.format(new Date());
    long sessionId = SharedPref.getLong(this, "bio_session_start_time", 0);

    mUserId = SharedPref.getString(this, "SelectedUser", "");

    // Now get the database object associated with this user

    try {
        mBioUserDao = getHelper().getBioUserDao();
        mBioSessionDao = getHelper().getBioSessionDao();

        QueryBuilder<BioUser, Integer> builder = mBioUserDao.queryBuilder();
        builder.where().eq(BioUser.NAME_FIELD_NAME, mUserId);
        builder.limit(1);
        //         builder.orderBy(ClickCount.DATE_FIELD_NAME, false).limit(30);
        List<BioUser> list = mBioUserDao.query(builder.prepare());

        if (list.size() == 1) {
            mCurrentBioUser = list.get(0);
        } else if (list.size() == 0) {
            try {
                mCurrentBioUser = new BioUser(mUserId, System.currentTimeMillis());
                mBioUserDao.create(mCurrentBioUser);
            } catch (SQLException e1) {
                Log.e(TAG, "Error creating user " + mUserId, e1);
            }
        } else {
            Log.e(TAG, "General Database error" + mUserId);
        }

    } catch (SQLException e) {
        Log.e(TAG, "Can't find user: " + mUserId, e);

    }

    mSignalImage.setImageResource(R.drawable.signal_bars0);

    // Check to see of there a device configured for EEG, if so then show the skin conductance meter
    String tmp = SharedPref.getString(this, "EEG", null);

    if (tmp != null) {
        mSignalImage.setVisibility(View.VISIBLE);
        mTextViewInstructions.setVisibility(View.VISIBLE);

    } else {
        mSignalImage.setVisibility(View.INVISIBLE);
        mTextViewInstructions.setVisibility(View.INVISIBLE);
    }

    mDataOutHandler = new DataOutHandler(this, mUserId, sessionDate, mAppId,
            DataOutHandler.DATA_TYPE_EXTERNAL_SENSOR, sessionId);

    if (mDatabaseEnabled) {
        TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        String myNumber = telephonyManager.getLine1Number();

        String remoteDatabaseUri = SharedPref.getString(this, "database_sync_name",
                getString(R.string.database_uri));
        //            remoteDatabaseUri += myNumber; 

        Log.d(TAG, "Initializing database at " + remoteDatabaseUri); // TODO: remove
        try {
            mDataOutHandler.initializeDatabase(dDatabaseName, dDesignDocName, dDesignDocId, byDateViewName,
                    remoteDatabaseUri);
        } catch (DataOutHandlerException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
        }
        mDataOutHandler.setRequiresAuthentication(false);
    }

    mBioDataProcessor.initialize(mDataOutHandler);

    mLoggingEnabled = SharedPref.getBoolean(this, "enable_logging", true);
    mDatabaseEnabled = SharedPref.getBoolean(this, "database_enabled", false);
    mAntHrmEnabled = SharedPref.getBoolean(this, "enable_ant_hrm", false);

    mInternalSensorMonitoring = SharedPref.getBoolean(this, "inernal_sensor_monitoring_enabled", false);

    if (mAntHrmEnabled) {
        mHeartRateSource = HEARTRATE_ANT;
    } else {
        mHeartRateSource = HEARTRATE_ZEPHYR;
    }

    if (mLoggingEnabled) {
        mDataOutHandler.enableLogging(this);
    }

    if (mLogCatEnabled) {
        mDataOutHandler.enableLogCat();
    }

    // Log the version
    try {
        PackageManager packageManager = getPackageManager();
        PackageInfo info = packageManager.getPackageInfo(getPackageName(), 0);
        mApplicationVersion = info.versionName;
        String versionString = mAppId + " application version: " + mApplicationVersion;

        DataOutPacket packet = new DataOutPacket();
        packet.add(DataOutHandlerTags.version, versionString);
        try {
            mDataOutHandler.handleDataOut(packet);
        } catch (DataOutHandlerException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
        }

    } catch (NameNotFoundException e) {
        Log.e(TAG, e.toString());
    }

    if (mInternalSensorMonitoring) {
        // IntentSender Launches our service scheduled with with the alarm manager 
        mBigBrotherService = PendingIntent.getService(MeditationActivity.this, 0,
                new Intent(MeditationActivity.this, BigBrotherService.class), 0);

        long firstTime = SystemClock.elapsedRealtime();
        // Schedule the alarm!
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, mPollingPeriod * 1000,
                mBigBrotherService);

        // Tell the user about what we did.
        Toast.makeText(MeditationActivity.this, R.string.service_scheduled, Toast.LENGTH_LONG).show();

    }

}

From source file:de.ub0r.android.websms.WebSMS.java

private void fetchSenderAndPrefixFromPhoneNumber() {
    final TelephonyManager tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
    if (tm == null) {
        return;//from   w ww.ja  v a  2  s.c  om
    }

    if (!requestPermission(android.Manifest.permission.READ_PHONE_STATE, PERMISSIONS_REQUEST_READ_PHONE_STATE,
            R.string.permissions_read_phone_state, null)) {
        return;
    }

    String number = tm.getLine1Number();
    Log.i(TAG, "line1: " + number);

    if (number != null && number.startsWith("00")) {
        number = number.replaceFirst("00", "+");
    }
    if (number != null && !TextUtils.isEmpty(number) && (number.startsWith("+"))) {
        final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(this);
        final Editor e = p.edit();
        if (TextUtils.isEmpty(p.getString(PREFS_SENDER, null))) {
            Log.i(TAG, "set number=" + number);
            e.putString(PREFS_SENDER, number);
        }
        if (TextUtils.isEmpty(p.getString(PREFS_DEFPREFIX, null))) {
            String prefix = de.ub0r.android.lib.Utils.getPrefixFromTelephoneNumber(number);
            if (!TextUtils.isEmpty(prefix)) {
                Log.i(TAG, "set prefix=" + prefix);
                e.putString(PREFS_DEFPREFIX, prefix);
            } else {
                Log.w(TAG, "unable to get prefix from number: " + number);
            }
        }
        e.apply();
    }
}

From source file:com.android.bluetooth.map.BluetoothMapContent.java

private void setFilterInfo(FilterInfo fi) {
    TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
    if (tm != null) {
        fi.phoneType = tm.getPhoneType();
        fi.phoneNum = tm.getLine1Number();
        fi.phoneAlphaTag = tm.getLine1AlphaTag();
        if (D)/*w w w .  ja v a  2 s.  c  o m*/
            Log.d(TAG, "phone type = " + fi.phoneType + " phone num = " + fi.phoneNum + " phone alpha tag = "
                    + fi.phoneAlphaTag);
    }
}

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

/**
 * Fetch all device runtime information.
 * @throws AndroidAgentException/*from   ww w.j a v a  2  s  . c  o  m*/
 */
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:org.wso2.iot.agent.services.DeviceInfoPayload.java

/**
 * Fetch all device runtime information.
 *
 * @throws AndroidAgentException on error
 *//*from  w  w w  .  j  a  v a2 s.  c o m*/
@SuppressLint("HardwareIds")
private void getInfo() throws AndroidAgentException {

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

    if (!CommonUtils.isServiceRunning(context, NetworkInfoService.class)) {
        Intent serviceIntent = new Intent(context, NetworkInfoService.class);
        context.startService(serviceIntent);
    }

    Location deviceLocation = CommonUtils.getLocation(context);
    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);

    if (telephonyManager != null && ActivityCompat.checkSelfPermission(context,
            Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
        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.FCM_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);

    if (telephonyManager != null && ActivityCompat.checkSelfPermission(context,
            Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
        String mPhoneNumber = telephonyManager.getLine1Number();
        if (mPhoneNumber != null) {
            property = new Device.Property();
            property.setName(Constants.Device.PHONE_NUMBER);
            property.setValue(mPhoneNumber);
            deviceInfoProperties.add(property);
        }
    }

    try {
        String network = NetworkInfoService.getNetworkStatus();
        if (network != null) {
            property = new Device.Property();
            property.setName(Constants.Device.NETWORK_INFO);
            property.setValue(network);
            properties.add(property);
        }
        if (Constants.WIFI_SCANNING_ENABLED) {
            // adding wifi scan results..
            property = new Device.Property();
            property.setName(Constants.Device.WIFI_SCAN_RESULT);
            property.setValue(NetworkInfoService.getWifiScanResult());
            properties.add(property);
        }
    } catch (AndroidAgentException e) {
        Log.e(TAG, "Error retrieving network status. " + e.getMessage());
    }

    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);
}