Example usage for android.hardware Sensor getMaximumRange

List of usage examples for android.hardware Sensor getMaximumRange

Introduction

In this page you can find the example usage for android.hardware Sensor getMaximumRange.

Prototype

public float getMaximumRange() 

Source Link

Usage

From source file:altermarkive.uploader.Report.java

@SuppressWarnings("unused")
public static String probe(Context context) throws JSONException {
    SensorManager manager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
    List<Sensor> list = manager.getSensorList(Sensor.TYPE_ALL);
    int[] types = new int[list.size()];
    String[] vendors = new String[list.size()];
    String[] names = new String[list.size()];
    float[] resolutions = new float[list.size()];
    int[] delays = new int[list.size()];
    float[] ranges = new float[list.size()];
    float[] powers = new float[list.size()];
    int i = 0;//from w  ww .  ja  v  a2s. c o  m
    for (Sensor sensor : list) {
        types[i] = sensor.getType();
        vendors[i] = sensor.getVendor();
        names[i] = sensor.getName();
        resolutions[i] = sensor.getResolution();
        delays[i] = sensor.getMinDelay();
        ranges[i] = sensor.getMaximumRange();
        powers[i] = sensor.getPower();
        i++;
    }
    return report(context, types, vendors, names, resolutions, delays, ranges, powers);
}

From source file:com.achep.acdisplay.services.activemode.sensors.ProximitySensor.java

@Override
public void onStart(@NonNull SensorManager sensorManager) {
    if (DEBUG)/*from   ww w  .  ja  v  a 2  s.  c  om*/
        Log.d(TAG, "Starting proximity sensor...");

    mHistory.clear();
    mHistory.add(new Event(false, getTimeNow()));

    Config.getInstance().registerListener(this);
    updateWave2WakeProgram();

    // Ignore pocket program's start delay,
    // so app can act just after it has started.
    mFirstChange = true;
    mPocketProgram.dataArray[0].timeMin = 0;

    Sensor proximitySensor = sensorManager.getDefaultSensor(getType());
    sensorManager.registerListener(this, proximitySensor, SensorManager.SENSOR_DELAY_NORMAL);

    mMaximumRange = proximitySensor.getMaximumRange();
    sAttached = true;
}

From source file:ch.bfh.sensordataprocessor.sensor.SensorDisplayFragment.java

public void displaySensor(Sensor sensor) {
    if (BuildConfig.DEBUG) {
        Log.d(TAG, "display the sensor");
    }/*from  w  w  w.j a v a  2  s  .c o m*/

    this.sensor = sensor;

    name.setText(sensor.getName());
    type.setText(String.valueOf(sensor.getType()));
    maxRange.setText(String.valueOf(sensor.getMaximumRange()));
    minDelay.setText(String.valueOf(sensor.getMinDelay()));
    power.setText(String.valueOf(sensor.getPower()));
    resolution.setText(String.valueOf(sensor.getResolution()));
    vendor.setText(String.valueOf(sensor.getVendor()));
    version.setText(String.valueOf(sensor.getVersion()));

    sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
}

From source file:com.tritop.androsense2.fragments.SensorsList.java

private List<Map<String, String>> parseAvailableSensors(List<Sensor> sList) {
    List<Map<String, String>> mList = new Vector<Map<String, String>>();
    HashMap<String, String> mSensorInfo;
    for (Sensor sensor : sList) {
        mSensorInfo = new HashMap<String, String>();
        mSensorInfo.put(SENSOR_KEY_NAME, sensor.getName());
        mSensorInfo.put(SENSOR_KEY_VENDOR, sensor.getVendor());
        mSensorInfo.put(SENSOR_KEY_VERSION, SensorInfo.getStringType(getActivity(), sensor.getType()) + " v"
                + String.valueOf(sensor.getVersion()));
        mSensorInfo.put(SENSOR_KEY_POWER, SensorInfo.formatSensorfloat(sensor.getPower(), 4) + " mA");
        mSensorInfo.put(SENSOR_KEY_MAXRANGE,
                SensorInfo.formatSensorfloat(sensor.getMaximumRange(), 3) + " max");
        mSensorInfo.put(SENSOR_KEY_RESOLUTION,
                SensorInfo.formatSensorfloat(sensor.getResolution(), 4) + " res");
        mList.add(mSensorInfo);/*  w  w  w . j  a v  a 2  s . c o m*/
    }
    return mList;

}

From source file:com.tritop.androsense2.fragments.SensorsListFragment.java

private List<Map<String, String>> parseAvailableSensors(List<Sensor> sList) {
    List<Map<String, String>> mList = new Vector<Map<String, String>>();
    HashMap<String, String> mSensorInfo;
    for (Sensor sensor : sList) {
        Log.d("SENSORLIST", sensor.getName());
        mSensorInfo = new HashMap<String, String>();
        mSensorInfo.put(SENSOR_KEY_NAME, sensor.getName());
        mSensorInfo.put(SENSOR_KEY_VENDOR, sensor.getVendor());
        mSensorInfo.put(SENSOR_KEY_VERSION, SensorInfo.getStringType(getActivity(), sensor.getType()) + " v"
                + String.valueOf(sensor.getVersion()));
        mSensorInfo.put(SENSOR_KEY_POWER, SensorInfo.formatSensorfloat(sensor.getPower(), 4) + " mA");
        mSensorInfo.put(SENSOR_KEY_MAXRANGE,
                SensorInfo.formatSensorfloat(sensor.getMaximumRange(), 3) + " max");
        mSensorInfo.put(SENSOR_KEY_RESOLUTION,
                SensorInfo.formatSensorfloat(sensor.getResolution(), 4) + " res");
        mList.add(mSensorInfo);/*  w  ww.j a  v  a  2 s  . c o m*/
    }
    return mList;

}

From source file:github.nisrulz.projecteasydeviceinfo.MainActivity.java

@TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
@Override//from  w  ww .  j  a  v a2s.com
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Data Array List of Info Object
    final ArrayList<String> data = new ArrayList<>();

    //Add Data
    ArrayMap<String, String> deviceDataMap = new ArrayMap<>();

    // Setup the value to be returned when result is either not found or invalid/null
    EasyDeviceInfo.setNotFoundVal("na");
    // Enable Debugging when in Debug build
    if (BuildConfig.DEBUG) {
        EasyDeviceInfo.debug();
    }

    // Library Info
    data.add(EasyDeviceInfo.getLibraryVersion());

    // ID Mod
    EasyIdMod easyIdMod = new EasyIdMod(this);

    String[] emailIds = easyIdMod.getAccounts();
    StringBuilder emailString = new StringBuilder();
    if (emailIds != null && emailIds.length > 0) {
        for (String e : emailIds) {
            emailString.append(e).append("\n");
        }
    } else {
        emailString.append("-");
    }

    EasyAdsMod easyAdsMod = new EasyAdsMod(this);
    easyAdsMod.getAndroidAdId(new EasyAdsMod.AdIdentifierCallback() {
        @Override
        public void onSuccess(String adIdentifier, boolean adDonotTrack) {
            // Add Data
            data.add("Android Advertiser ID :" + adIdentifier);
            data.add("Ad Do not Track :" + adDonotTrack);
            adapter.notifyDataSetChanged();
        }
    });

    // Config Mod
    EasyConfigMod easyConfigMod = new EasyConfigMod(this);
    deviceDataMap.put("Time (ms)", String.valueOf(easyConfigMod.getTime()));
    deviceDataMap.put("Formatted Time (24Hrs)", easyConfigMod.getFormattedTime());
    deviceDataMap.put("UpTime (ms)", String.valueOf(easyConfigMod.getUpTime()));
    deviceDataMap.put("Formatted Up Time (24Hrs)", easyConfigMod.getFormattedUpTime());
    deviceDataMap.put("Date", String.valueOf(easyConfigMod.getCurrentDate()));
    deviceDataMap.put("Formatted Date", easyConfigMod.getFormattedDate());
    deviceDataMap.put("SD Card available", String.valueOf(easyConfigMod.hasSdCard()));
    deviceDataMap.put("Running on emulator", String.valueOf(easyConfigMod.isRunningOnEmulator()));

    @RingerMode
    int ringermode = easyConfigMod.getDeviceRingerMode();
    switch (ringermode) {
    case RingerMode.NORMAL:
        deviceDataMap.put(getString(R.string.ringer_mode), "normal");
        break;
    case RingerMode.VIBRATE:
        deviceDataMap.put(getString(R.string.ringer_mode), "vibrate");
        break;
    case RingerMode.SILENT:
    default:
        deviceDataMap.put(getString(R.string.ringer_mode), "silent");
        break;
    }

    // Fingerprint Mod
    EasyFingerprintMod easyFingerprintMod = new EasyFingerprintMod(this);
    deviceDataMap.put("Is Fingerprint Sensor present?",
            String.valueOf(easyFingerprintMod.isFingerprintSensorPresent()));
    deviceDataMap.put("Are fingerprints enrolled",
            String.valueOf(easyFingerprintMod.areFingerprintsEnrolled()));

    // Sensor Mod
    EasySensorMod easySensorMod = new EasySensorMod(this);
    List<Sensor> list = easySensorMod.getAllSensors();
    for (Sensor s : list) {
        if (s != null) {
            StringBuilder stringBuilder = new StringBuilder().append("\nVendor : ").append(s.getVendor())
                    .append("\n").append("Version : ").append(s.getVersion()).append("\n").append("Power : ")
                    .append(s.getPower()).append("\n").append("Resolution : ").append(s.getResolution())
                    .append("\n").append("Max Range : ").append(s.getMaximumRange());
            deviceDataMap.put("Sensor Name - " + s.getName(), stringBuilder.toString());
        } else {
            deviceDataMap.put("Sensor", "N/A");
        }
    }

    // SIM Mod
    EasySimMod easySimMod = new EasySimMod(this);
    deviceDataMap.put("IMSI", easySimMod.getIMSI());
    deviceDataMap.put("SIM Serial Number", easySimMod.getSIMSerial());
    deviceDataMap.put("Country", easySimMod.getCountry());
    deviceDataMap.put("Carrier", easySimMod.getCarrier());
    deviceDataMap.put("SIM Network Locked", String.valueOf(easySimMod.isSimNetworkLocked()));
    deviceDataMap.put("Is Multi SIM", String.valueOf(easySimMod.isMultiSim()));
    deviceDataMap.put("Number of active SIM", String.valueOf(easySimMod.getNumberOfActiveSim()));

    if (easySimMod.isMultiSim()) {
        List<SubscriptionInfo> activeMultiSimInfo = easySimMod.getActiveMultiSimInfo();
        if (activeMultiSimInfo != null) {
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < activeMultiSimInfo.size(); i++) {
                stringBuilder.append("\nSIM ").append(i).append(" Info").append("\nPhone Number :")
                        .append(activeMultiSimInfo.get(i).getNumber()).append("\n").append("Carrier Name :")
                        .append(activeMultiSimInfo.get(i).getCarrierName()).append("\n").append("Country :")
                        .append(activeMultiSimInfo.get(i).getCountryIso()).append("\n").append("Roaming :")
                        .append(activeMultiSimInfo.get(i)
                                .getDataRoaming() == SubscriptionManager.DATA_ROAMING_ENABLE)
                        .append("\n").append("Display Name :")
                        .append(activeMultiSimInfo.get(i).getDisplayName()).append("\n").append("Sim Slot  :")
                        .append(activeMultiSimInfo.get(i).getSimSlotIndex()).append("\n");
            }
            deviceDataMap.put("Multi SIM Info", stringBuilder.toString());
        }
    }

    // Device Mod
    EasyDeviceMod easyDeviceMod = new EasyDeviceMod(this);
    deviceDataMap.put("Language", easyDeviceMod.getLanguage());
    deviceDataMap.put("Android ID", easyIdMod.getAndroidID());
    deviceDataMap.put("IMEI", easyDeviceMod.getIMEI());
    deviceDataMap.put("User-Agent", easyIdMod.getUA());
    deviceDataMap.put("GSF ID", easyIdMod.getGSFID());
    deviceDataMap.put("Pseudo ID", easyIdMod.getPseudoUniqueID());
    deviceDataMap.put("Device Serial", easyDeviceMod.getSerial());
    deviceDataMap.put("Manufacturer", easyDeviceMod.getManufacturer());
    deviceDataMap.put("Model", easyDeviceMod.getModel());
    deviceDataMap.put("OS Codename", easyDeviceMod.getOSCodename());
    deviceDataMap.put("OS Version", easyDeviceMod.getOSVersion());
    deviceDataMap.put("Display Version", easyDeviceMod.getDisplayVersion());
    deviceDataMap.put("Phone Number", easyDeviceMod.getPhoneNo());
    deviceDataMap.put("Radio Version", easyDeviceMod.getRadioVer());
    deviceDataMap.put("Product ", easyDeviceMod.getProduct());
    deviceDataMap.put("Device", easyDeviceMod.getDevice());
    deviceDataMap.put("Board", easyDeviceMod.getBoard());
    deviceDataMap.put("Hardware", easyDeviceMod.getHardware());
    deviceDataMap.put("BootLoader", easyDeviceMod.getBootloader());
    deviceDataMap.put("Device Rooted", String.valueOf(easyDeviceMod.isDeviceRooted()));
    deviceDataMap.put("Fingerprint", easyDeviceMod.getFingerprint());
    deviceDataMap.put("Build Brand", easyDeviceMod.getBuildBrand());
    deviceDataMap.put("Build Host", easyDeviceMod.getBuildHost());
    deviceDataMap.put("Build Tag", easyDeviceMod.getBuildTags());
    deviceDataMap.put("Build Time", String.valueOf(easyDeviceMod.getBuildTime()));
    deviceDataMap.put("Build User", easyDeviceMod.getBuildUser());
    deviceDataMap.put("Build Version Release", easyDeviceMod.getBuildVersionRelease());
    deviceDataMap.put("Screen Display ID", easyDeviceMod.getScreenDisplayID());
    deviceDataMap.put("Build Version Codename", easyDeviceMod.getBuildVersionCodename());
    deviceDataMap.put("Build Version Increment", easyDeviceMod.getBuildVersionIncremental());
    deviceDataMap.put("Build Version SDK", String.valueOf(easyDeviceMod.getBuildVersionSDK()));
    deviceDataMap.put("Build ID", easyDeviceMod.getBuildID());

    @DeviceType
    int deviceType = easyDeviceMod.getDeviceType(this);
    switch (deviceType) {
    case DeviceType.WATCH:
        deviceDataMap.put(getString(R.string.device_type), "watch");
        break;
    case DeviceType.PHONE:
        deviceDataMap.put(getString(R.string.device_type), "phone");
        break;
    case DeviceType.PHABLET:
        deviceDataMap.put(getString(R.string.device_type), "phablet");
        break;
    case DeviceType.TABLET:
        deviceDataMap.put(getString(R.string.device_type), "tablet");
        break;
    case DeviceType.TV:
        deviceDataMap.put(getString(R.string.device_type), "tv");
        break;
    default:
        //do nothing
        break;
    }

    @PhoneType
    int phoneType = easyDeviceMod.getPhoneType();
    switch (phoneType) {

    case PhoneType.CDMA:
        deviceDataMap.put(getString(R.string.phone_type), "CDMA");
        break;
    case PhoneType.GSM:
        deviceDataMap.put(getString(R.string.phone_type), "GSM");
        break;
    case PhoneType.NONE:
        deviceDataMap.put(getString(R.string.phone_type), "None");
        break;
    default:
        deviceDataMap.put(getString(R.string.phone_type), "Unknown");
        break;
    }

    @OrientationType
    int orientationType = easyDeviceMod.getOrientation(this);
    switch (orientationType) {
    case OrientationType.LANDSCAPE:
        deviceDataMap.put(getString(R.string.orientation), "Landscape");
        break;
    case OrientationType.PORTRAIT:
        deviceDataMap.put(getString(R.string.orientation), "Portrait");
        break;
    case OrientationType.UNKNOWN:
    default:
        deviceDataMap.put(getString(R.string.orientation), "Unknown");
        break;
    }

    // App Mod
    EasyAppMod easyAppMod = new EasyAppMod(this);
    deviceDataMap.put("Installer Store", easyAppMod.getStore());
    deviceDataMap.put("App Name", easyAppMod.getAppName());
    deviceDataMap.put("Package Name", easyAppMod.getPackageName());
    deviceDataMap.put("Activity Name", easyAppMod.getActivityName());
    deviceDataMap.put("App version", easyAppMod.getAppVersion());
    deviceDataMap.put("App versioncode", easyAppMod.getAppVersionCode());
    deviceDataMap.put("Does app have Camera permission?",
            String.valueOf(easyAppMod.isPermissionGranted(Manifest.permission.CAMERA)));

    //Network Mod
    EasyNetworkMod easyNetworkMod = new EasyNetworkMod(this);
    deviceDataMap.put("WIFI MAC Address", easyNetworkMod.getWifiMAC());
    deviceDataMap.put("WIFI LinkSpeed", easyNetworkMod.getWifiLinkSpeed());
    deviceDataMap.put("WIFI SSID", easyNetworkMod.getWifiSSID());
    deviceDataMap.put("WIFI BSSID", easyNetworkMod.getWifiBSSID());
    deviceDataMap.put("IPv4 Address", easyNetworkMod.getIPv4Address());
    deviceDataMap.put("IPv6 Address", easyNetworkMod.getIPv6Address());
    deviceDataMap.put("Network Available", String.valueOf(easyNetworkMod.isNetworkAvailable()));
    deviceDataMap.put("Wi-Fi enabled", String.valueOf(easyNetworkMod.isWifiEnabled()));

    @NetworkType
    int networkType = easyNetworkMod.getNetworkType();

    switch (networkType) {
    case NetworkType.CELLULAR_UNKNOWN:
        deviceDataMap.put(getString(R.string.network_type), "Cellular Unknown");
        break;
    case NetworkType.CELLULAR_UNIDENTIFIED_GEN:
        deviceDataMap.put(getString(R.string.network_type), "Cellular Unidentified Generation");
        break;
    case NetworkType.CELLULAR_2G:
        deviceDataMap.put(getString(R.string.network_type), "Cellular 2G");
        break;
    case NetworkType.CELLULAR_3G:
        deviceDataMap.put(getString(R.string.network_type), "Cellular 3G");
        break;
    case NetworkType.CELLULAR_4G:
        deviceDataMap.put(getString(R.string.network_type), "Cellular 4G");
        break;

    case NetworkType.WIFI_WIFIMAX:
        deviceDataMap.put(getString(R.string.network_type), "Wifi/WifiMax");
        break;
    case NetworkType.UNKNOWN:
    default:
        deviceDataMap.put(getString(R.string.network_type), "Unknown");
        break;
    }

    // Battery Mod
    EasyBatteryMod easyBatteryMod = new EasyBatteryMod(this);
    deviceDataMap.put("Battery Percentage", String.valueOf(easyBatteryMod.getBatteryPercentage()) + "%");
    deviceDataMap.put("Is device charging", String.valueOf(easyBatteryMod.isDeviceCharging()));
    deviceDataMap.put("Battery present", String.valueOf(easyBatteryMod.isBatteryPresent()));
    deviceDataMap.put("Battery technology", String.valueOf(easyBatteryMod.getBatteryTechnology()));
    deviceDataMap.put("Battery temperature", String.valueOf(easyBatteryMod.getBatteryTemperature()) + " deg C");
    deviceDataMap.put("Battery voltage", String.valueOf(easyBatteryMod.getBatteryVoltage()) + " mV");

    @BatteryHealth
    int batteryHealth = easyBatteryMod.getBatteryHealth();
    switch (batteryHealth) {
    case BatteryHealth.GOOD:
        deviceDataMap.put("Battery health", "Good");
        break;
    case BatteryHealth.HAVING_ISSUES:
    default:
        deviceDataMap.put("Battery health", "Having issues");
        break;
    }

    @ChargingVia
    int isChargingVia = easyBatteryMod.getChargingSource();
    switch (isChargingVia) {
    case ChargingVia.AC:
        deviceDataMap.put(getString(R.string.device_charging_via), "AC");
        break;
    case ChargingVia.USB:
        deviceDataMap.put(getString(R.string.device_charging_via), "USB");
        break;
    case ChargingVia.WIRELESS:
        deviceDataMap.put(getString(R.string.device_charging_via), "Wireless");
        break;
    case ChargingVia.UNKNOWN_SOURCE:
    default:
        deviceDataMap.put(getString(R.string.device_charging_via), "Unknown Source");
        break;
    }

    //Bluetooth Mod
    EasyBluetoothMod easyBluetoothMod = new EasyBluetoothMod(this);
    deviceDataMap.put("BT MAC Address", easyBluetoothMod.getBluetoothMAC());

    // Display Mod
    EasyDisplayMod easyDisplayMod = new EasyDisplayMod(this);
    deviceDataMap.put("Display Resolution", easyDisplayMod.getResolution());
    deviceDataMap.put("Screen Density", easyDisplayMod.getDensity());
    deviceDataMap.put("Screen Size", String.valueOf(easyDisplayMod.getPhysicalSize()));
    deviceDataMap.put("Screen Refresh rate", String.valueOf(easyDisplayMod.getRefreshRate()) + " Hz");

    deviceDataMap.put("Email ID", emailString.toString());

    // Location Mod
    EasyLocationMod easyLocationMod = new EasyLocationMod(this);
    double[] l = easyLocationMod.getLatLong();
    String lat = String.valueOf(l[0]);
    String lon = String.valueOf(l[1]);
    deviceDataMap.put("Latitude", lat);
    deviceDataMap.put("Longitude", lon);

    // Memory Mod
    EasyMemoryMod easyMemoryMod = new EasyMemoryMod(this);
    deviceDataMap.put("Total RAM",
            String.valueOf(easyMemoryMod.convertToGb(easyMemoryMod.getTotalRAM())) + " Gb");
    deviceDataMap.put("Available Internal Memory",
            String.valueOf(easyMemoryMod.convertToGb(easyMemoryMod.getAvailableInternalMemorySize())) + " Gb");
    deviceDataMap.put("Available External Memory",
            String.valueOf(easyMemoryMod.convertToGb(easyMemoryMod.getAvailableExternalMemorySize())) + " Gb");
    deviceDataMap.put("Total Internal Memory",
            String.valueOf(easyMemoryMod.convertToGb(easyMemoryMod.getTotalInternalMemorySize())) + " Gb");
    deviceDataMap.put("Total External memory",
            String.valueOf(easyMemoryMod.convertToGb(easyMemoryMod.getTotalExternalMemorySize())) + " Gb");

    // CPU Mod
    EasyCpuMod easyCpuMod = new EasyCpuMod();
    deviceDataMap.put("Supported ABIS", easyCpuMod.getStringSupportedABIS());
    deviceDataMap.put("Supported 32 bit ABIS", easyCpuMod.getStringSupported32bitABIS());
    deviceDataMap.put("Supported 64 bit ABIS", easyCpuMod.getStringSupported64bitABIS());

    // NFC Mod
    EasyNfcMod easyNfcMod = new EasyNfcMod(this);
    deviceDataMap.put("is NFC present", String.valueOf(easyNfcMod.isNfcPresent()));
    deviceDataMap.put("is NFC enabled", String.valueOf(easyNfcMod.isNfcEnabled()));

    for (String key : deviceDataMap.keySet()) {
        data.add(key + " : " + deviceDataMap.get(key));
    }

    ListView lv = (ListView) findViewById(R.id.listview);
    adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, data);
    lv.setAdapter(adapter);
}

From source file:org.openchaos.android.fooping.service.PingService.java

@Override
protected void onHandleIntent(Intent intent) {
    String clientID = prefs.getString("ClientID", "unknown");
    long ts = System.currentTimeMillis();

    Log.d(tag, "onHandleIntent()");

    // always send ping
    if (true) {/*from   ww  w  . jav  a 2 s  . co m*/
        try {
            JSONObject json = new JSONObject();
            json.put("client", clientID);
            json.put("type", "ping");
            json.put("ts", ts);

            sendMessage(json);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            e.printStackTrace();
        }
    }

    // http://developer.android.com/training/monitoring-device-state/battery-monitoring.html
    // http://developer.android.com/reference/android/os/BatteryManager.html
    if (prefs.getBoolean("UseBattery", false)) {
        try {
            JSONObject json = new JSONObject();
            json.put("client", clientID);
            json.put("type", "battery");
            json.put("ts", ts);

            Intent batteryStatus = registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
            if (batteryStatus != null) {
                JSONObject bat_data = new JSONObject();

                int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
                int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
                if (level >= 0 && scale > 0) {
                    bat_data.put("pct", roundValue(((double) level / (double) scale) * 100, 2));
                } else {
                    Log.w(tag, "Battery level unknown");
                    bat_data.put("pct", -1);
                }
                bat_data.put("health", batteryStatus.getIntExtra(BatteryManager.EXTRA_HEALTH, -1));
                bat_data.put("status", batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1));
                bat_data.put("plug", batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1));
                bat_data.put("volt", batteryStatus.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1));
                bat_data.put("temp", batteryStatus.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1));
                bat_data.put("tech", batteryStatus.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY));
                // bat_data.put("present", batteryStatus.getBooleanExtra(BatteryManager.EXTRA_PRESENT, false));

                json.put("battery", bat_data);
            }

            sendMessage(json);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            e.printStackTrace();
        }
    }

    // http://developer.android.com/guide/topics/location/strategies.html
    // http://developer.android.com/reference/android/location/LocationManager.html
    if (prefs.getBoolean("UseGPS", false)) {
        try {
            JSONObject json = new JSONObject();
            json.put("client", clientID);
            json.put("type", "loc_gps");
            json.put("ts", ts);

            if (lm == null) {
                lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            }

            Location last_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (last_loc != null) {
                JSONObject loc_data = new JSONObject();

                loc_data.put("ts", last_loc.getTime());
                loc_data.put("lat", last_loc.getLatitude());
                loc_data.put("lon", last_loc.getLongitude());
                if (last_loc.hasAltitude())
                    loc_data.put("alt", roundValue(last_loc.getAltitude(), 4));
                if (last_loc.hasAccuracy())
                    loc_data.put("acc", roundValue(last_loc.getAccuracy(), 4));
                if (last_loc.hasSpeed())
                    loc_data.put("speed", roundValue(last_loc.getSpeed(), 4));
                if (last_loc.hasBearing())
                    loc_data.put("bearing", roundValue(last_loc.getBearing(), 4));

                json.put("loc_gps", loc_data);
            }

            sendMessage(json);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            e.printStackTrace();
        }
    }

    if (prefs.getBoolean("UseNetwork", false)) {
        try {
            JSONObject json = new JSONObject();
            json.put("client", clientID);
            json.put("type", "loc_net");
            json.put("ts", ts);

            if (lm == null) {
                lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            }

            Location last_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            if (last_loc != null) {
                JSONObject loc_data = new JSONObject();

                loc_data.put("ts", last_loc.getTime());
                loc_data.put("lat", last_loc.getLatitude());
                loc_data.put("lon", last_loc.getLongitude());
                if (last_loc.hasAltitude())
                    loc_data.put("alt", roundValue(last_loc.getAltitude(), 4));
                if (last_loc.hasAccuracy())
                    loc_data.put("acc", roundValue(last_loc.getAccuracy(), 4));
                if (last_loc.hasSpeed())
                    loc_data.put("speed", roundValue(last_loc.getSpeed(), 4));
                if (last_loc.hasBearing())
                    loc_data.put("bearing", roundValue(last_loc.getBearing(), 4));

                json.put("loc_net", loc_data);
            }

            sendMessage(json);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            e.printStackTrace();
        }
    }

    // http://developer.android.com/reference/android/net/wifi/WifiManager.html
    if (prefs.getBoolean("UseWIFI", false)) {
        try {
            JSONObject json = new JSONObject();
            json.put("client", clientID);
            json.put("type", "wifi");
            json.put("ts", ts);

            if (wm == null) {
                wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            }

            List<ScanResult> wifiScan = wm.getScanResults();
            if (wifiScan != null) {
                JSONArray wifi_list = new JSONArray();

                for (ScanResult wifi : wifiScan) {
                    JSONObject wifi_data = new JSONObject();

                    wifi_data.put("BSSID", wifi.BSSID);
                    wifi_data.put("SSID", wifi.SSID);
                    wifi_data.put("freq", wifi.frequency);
                    wifi_data.put("level", wifi.level);
                    // wifi_data.put("cap", wifi.capabilities);
                    // wifi_data.put("ts", wifi.timestamp);

                    wifi_list.put(wifi_data);
                }

                json.put("wifi", wifi_list);
            }

            sendMessage(json);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            e.printStackTrace();
        }
    }

    // TODO: cannot poll sensors. register receiver to cache sensor data
    // http://developer.android.com/guide/topics/sensors/sensors_overview.html
    // http://developer.android.com/reference/android/hardware/SensorManager.html
    if (prefs.getBoolean("UseSensors", false)) {
        try {
            JSONObject json = new JSONObject();
            json.put("client", clientID);
            json.put("type", "sensors");
            json.put("ts", ts);

            if (sm == null) {
                sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
            }

            List<Sensor> sensors = sm.getSensorList(Sensor.TYPE_ALL);
            if (sensors != null) {
                JSONArray sensor_list = new JSONArray();

                for (Sensor sensor : sensors) {
                    JSONObject sensor_info = new JSONObject();

                    sensor_info.put("name", sensor.getName());
                    sensor_info.put("type", sensor.getType());
                    sensor_info.put("vendor", sensor.getVendor());
                    sensor_info.put("version", sensor.getVersion());
                    sensor_info.put("power", roundValue(sensor.getPower(), 4));
                    sensor_info.put("resolution", roundValue(sensor.getResolution(), 4));
                    sensor_info.put("range", roundValue(sensor.getMaximumRange(), 4));

                    sensor_list.put(sensor_info);
                }

                json.put("sensors", sensor_list);
            }

            sendMessage(json);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            e.printStackTrace();
        }
    }

    // http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html
    // http://developer.android.com/reference/android/net/ConnectivityManager.html
    if (prefs.getBoolean("UseConn", false)) {
        try {
            JSONObject json = new JSONObject();
            json.put("client", clientID);
            json.put("type", "conn");
            json.put("ts", ts);

            if (cm == null) {
                cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            }

            // TODO: add active/all preferences below UseConn
            if (prefs.getBoolean("UseConnActive", true)) {
                NetworkInfo net = cm.getActiveNetworkInfo();
                if (net != null) {
                    JSONObject net_data = new JSONObject();

                    net_data.put("type", net.getTypeName());
                    net_data.put("subtype", net.getSubtypeName());
                    net_data.put("connected", net.isConnected());
                    net_data.put("available", net.isAvailable());
                    net_data.put("roaming", net.isRoaming());
                    net_data.put("failover", net.isFailover());
                    if (net.getReason() != null)
                        net_data.put("reason", net.getReason());
                    if (net.getExtraInfo() != null)
                        net_data.put("extra", net.getExtraInfo());

                    json.put("conn_active", net_data);
                }
            }

            if (prefs.getBoolean("UseConnAll", false)) {
                NetworkInfo[] nets = cm.getAllNetworkInfo();
                if (nets != null) {
                    JSONArray net_list = new JSONArray();

                    for (NetworkInfo net : nets) {
                        JSONObject net_data = new JSONObject();

                        net_data.put("type", net.getTypeName());
                        net_data.put("subtype", net.getSubtypeName());
                        net_data.put("connected", net.isConnected());
                        net_data.put("available", net.isAvailable());
                        net_data.put("roaming", net.isRoaming());
                        net_data.put("failover", net.isFailover());
                        if (net.getReason() != null)
                            net_data.put("reason", net.getReason());
                        if (net.getExtraInfo() != null)
                            net_data.put("extra", net.getExtraInfo());

                        net_list.put(net_data);
                    }

                    json.put("conn_all", net_list);
                }
            }

            sendMessage(json);
        } catch (Exception e) {
            Log.e(tag, e.toString());
            e.printStackTrace();
        }
    }

    if (!PingServiceReceiver.completeWakefulIntent(intent)) {
        Log.w(tag, "completeWakefulIntent() failed. no active wake lock?");
    }
}

From source file:org.thecongers.mtpms.MainActivity.java

@SuppressLint("HandlerLeak")
@Override/*from   w w  w . j a  v  a  2  s.c o m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    setTitle(R.string.app_name);

    layoutFront = (LinearLayout) findViewById(R.id.layoutFront);
    layoutRear = (LinearLayout) findViewById(R.id.layoutRear);
    txtFrontPressure = (TextView) findViewById(R.id.txtFrontPressure);
    txtFrontTemperature = (TextView) findViewById(R.id.txtFrontTemperature);
    txtFrontVoltage = (TextView) findViewById(R.id.txtFrontVoltage);
    txtRearPressure = (TextView) findViewById(R.id.txtRearPressure);
    txtRearTemperature = (TextView) findViewById(R.id.txtRearTemperature);
    txtRearVoltage = (TextView) findViewById(R.id.txtRearVoltage);
    txtOutput = (TextView) findViewById(R.id.txtOutput);
    View myView = findViewById(R.id.appLayout);
    root = myView.getRootView();

    sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    // Keep screen on
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    // Watch for Bluetooth Changes
    IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
    IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
    IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    this.registerReceiver(btReceiver, filter1);
    this.registerReceiver(btReceiver, filter2);
    this.registerReceiver(btReceiver, filter3);

    sensorDB = new SensorIdDatabase(this);

    // Backgrounds
    background = this.getResources().getDrawable(R.drawable.rectangle_bordered);
    redBackground = this.getResources().getDrawable(R.drawable.rectangle_bordered_red);
    backgroundDark = this.getResources().getDrawable(R.drawable.rectangle_bordered_dark);
    redBackgroundDark = this.getResources().getDrawable(R.drawable.rectangle_bordered_red_dark);
    txtOutBackground = this.getResources().getDrawable(R.drawable.rectangle);
    txtOutBackgroundDark = this.getResources().getDrawable(R.drawable.rectangle_dark);

    // Update textViews with select units
    String pressureFormat = sharedPrefs.getString("prefpressuref", "0");
    String pressureUnit = "psi";
    if (pressureFormat.contains("1")) {
        // KPa
        pressureUnit = "KPa";
    } else if (pressureFormat.contains("2")) {
        // Kg-f
        pressureUnit = "Kg-f";
    } else if (pressureFormat.contains("3")) {
        // Bar
        pressureUnit = "Bar";
    }
    String temperatureUnit = "C";
    if (sharedPrefs.getString("preftempf", "0").contains("0")) {
        // F
        temperatureUnit = "F";
    }

    txtFrontPressure.setText("--- " + pressureUnit);
    txtFrontTemperature.setText("--- " + temperatureUnit);
    txtFrontVoltage.setText("--- V");
    txtRearPressure.setText("--- " + pressureUnit);
    txtRearTemperature.setText("--- " + temperatureUnit);
    txtRearVoltage.setText("--- V");

    // Set initial color scheme
    if (!sharedPrefs.getBoolean("prefNightMode", false)) {
        root.setBackgroundColor(getResources().getColor(android.R.color.white));
        layoutFront.setBackground(background);
        layoutRear.setBackground(background);
        txtFrontPressure.setTextColor(getResources().getColor(android.R.color.black));
        txtFrontTemperature.setTextColor(getResources().getColor(android.R.color.black));
        txtFrontVoltage.setTextColor(getResources().getColor(android.R.color.black));
        txtRearPressure.setTextColor(getResources().getColor(android.R.color.black));
        txtRearTemperature.setTextColor(getResources().getColor(android.R.color.black));
        txtRearVoltage.setTextColor(getResources().getColor(android.R.color.black));
        txtOutput.setBackground(txtOutBackground);
        txtOutput.setTextColor(getResources().getColor(android.R.color.black));
    } else {
        root.setBackgroundColor(getResources().getColor(android.R.color.black));
        layoutFront.setBackground(backgroundDark);
        layoutRear.setBackground(backgroundDark);
        txtFrontPressure.setTextColor(getResources().getColor(android.R.color.white));
        txtFrontTemperature.setTextColor(getResources().getColor(android.R.color.white));
        txtFrontVoltage.setTextColor(getResources().getColor(android.R.color.white));
        txtRearPressure.setTextColor(getResources().getColor(android.R.color.white));
        txtRearTemperature.setTextColor(getResources().getColor(android.R.color.white));
        txtRearVoltage.setTextColor(getResources().getColor(android.R.color.white));
        txtOutput.setBackground(txtOutBackgroundDark);
        txtOutput.setTextColor(getResources().getColor(android.R.color.white));
    }

    // Check if there are sensor to wheel mappings
    if (sharedPrefs.getString("prefFrontID", "").equals("")
            && sharedPrefs.getString("prefRearID", "").equals("")) {
        new AlertDialog.Builder(this).setTitle(R.string.alert_setup_title)
                .setMessage(R.string.alert_setup_message).setNeutralButton(R.string.alert_setup_button, null)
                .show();
    }

    sensorMessages = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case RECEIVE_MESSAGE:
                // Message received
                Log.d(TAG, "Serial Message Received, Length: " + msg.arg1);
                // Check to see if message is the correct size
                if (msg.arg1 == 13) {
                    byte[] readBuf = (byte[]) msg.obj;

                    // Validate against checksum
                    int calculatedCheckSum = readBuf[4] + readBuf[5] + readBuf[6] + readBuf[7] + readBuf[8]
                            + readBuf[9] + readBuf[10];
                    if (calculatedCheckSum == readBuf[11]) {
                        // Convert to hex
                        String[] hexData = new String[13];
                        StringBuilder sbhex = new StringBuilder();
                        for (int i = 0; i < msg.arg1; i++) {
                            hexData[i] = String.format("%02X", readBuf[i]);
                            sbhex.append(hexData[i]);
                        }

                        // Get sensor position
                        String position = hexData[3];
                        // Get sensor ID
                        StringBuilder sensorID = new StringBuilder();
                        sensorID.append(hexData[4]);
                        sensorID.append(hexData[5]);
                        sensorID.append(hexData[6]);
                        sensorID.append(hexData[7]);

                        // Check if sensor ID is new
                        boolean checkID = sensorDB.sensorIdExists(sensorID.toString());
                        if (!checkID) {
                            // Add sensor ID to db
                            sensorDB.addID(sensorID.toString());
                            Toast.makeText(MainActivity.this, getResources().getString(R.string.toast_newSensor)
                                    + " " + sensorID.toString(), Toast.LENGTH_LONG).show();
                        }
                        // Only parse message if there is one or more sensor mappings
                        String prefFrontID = sharedPrefs.getString("prefFrontID", "");
                        String prefRearID = sharedPrefs.getString("prefRearID", "");
                        if (!prefFrontID.equals("") || !prefRearID.equals("")) {
                            try {
                                // Get temperature
                                int tempC = Integer.parseInt(hexData[8], 16) - 50;
                                double temp = tempC;
                                String temperatureUnit = "C";
                                // Get tire pressure
                                int psi = Integer.parseInt(hexData[9], 16);
                                double pressure = psi;
                                String pressureUnit = "psi";
                                // Get battery voltage
                                double voltage = Integer.parseInt(hexData[10], 16) / 50;
                                // Get pressure thresholds
                                int fLowPressure = Integer
                                        .parseInt(sharedPrefs.getString("prefFrontLowPressure", "30"));
                                int fHighPressure = Integer
                                        .parseInt(sharedPrefs.getString("prefFrontHighPressure", "46"));
                                int rLowPressure = Integer
                                        .parseInt(sharedPrefs.getString("prefRearLowPressure", "30"));
                                int rHighPressure = Integer
                                        .parseInt(sharedPrefs.getString("prefRearHighPressure", "46"));
                                if (sharedPrefs.getString("preftempf", "0").contains("0")) {
                                    // F
                                    temp = (9.0 / 5.0) * tempC + 32.0;
                                    temperatureUnit = "F";
                                }
                                int formattedTemperature = (int) (temp + 0.5d);
                                String pressureFormat = sharedPrefs.getString("prefpressuref", "0");
                                if (pressureFormat.contains("1")) {
                                    // KPa
                                    pressure = psi * 6.894757293168361;
                                    pressureUnit = "KPa";
                                } else if (pressureFormat.contains("2")) {
                                    // Kg-f
                                    pressure = psi * 0.070306957965539;
                                    pressureUnit = "Kg-f";
                                } else if (pressureFormat.contains("3")) {
                                    // Bar
                                    pressure = psi * 0.0689475729;
                                    pressureUnit = "Bar";
                                }
                                int formattedPressure = (int) (pressure + 0.5d);
                                // Get checksum
                                String checksum = hexData[11];
                                Log.d(TAG,
                                        "Sensor ID: " + sensorID.toString() + ", Sensor Position: " + position
                                                + ", Temperature(" + temperatureUnit + "): "
                                                + String.valueOf(temp) + ", Pressure(" + pressureUnit + "): "
                                                + String.valueOf(pressure) + ", Voltage: "
                                                + String.valueOf(voltage) + ", Checksum: " + checksum
                                                + ", Data: " + sbhex.toString() + ", Bytes:" + msg.arg1);

                                if (sensorID.toString().equals(prefFrontID)) {
                                    Log.d(TAG, "Front ID matched");
                                    // Check for data logging enabled
                                    if (sharedPrefs.getBoolean("prefDataLogging", false)) {
                                        // Log data
                                        if (logger == null) {
                                            logger = new LogData();
                                        }
                                        logger.write("front", String.valueOf(psi), String.valueOf(tempC),
                                                String.valueOf(voltage));
                                    }

                                    // Set front tire status
                                    if (psi <= fLowPressure) {
                                        frontStatus = 1;
                                    } else if (psi >= fHighPressure) {
                                        frontStatus = 2;
                                    } else {
                                        frontStatus = 0;
                                    }

                                    txtFrontPressure
                                            .setText(String.valueOf(formattedPressure) + " " + pressureUnit);
                                    txtFrontTemperature.setText(
                                            String.valueOf(formattedTemperature) + " " + temperatureUnit);
                                    txtFrontVoltage.setText(String.format("%.2f", voltage) + " V");
                                } else if (sensorID.toString().equals(prefRearID)) {
                                    Log.d(TAG, "Rear ID matched");
                                    // Check for data logging enabled
                                    if (sharedPrefs.getBoolean("prefDataLogging", false)) {
                                        // Log data
                                        if (logger == null) {
                                            logger = new LogData();
                                        }
                                        logger.write("rear", String.valueOf(psi), String.valueOf(tempC),
                                                String.valueOf(voltage));
                                    }

                                    // Set rear tire status
                                    if (psi <= rLowPressure) {
                                        rearStatus = 1;
                                    } else if (psi >= rHighPressure) {
                                        rearStatus = 2;
                                    } else {
                                        rearStatus = 0;
                                    }
                                    txtRearPressure
                                            .setText(String.valueOf(formattedPressure) + " " + pressureUnit);
                                    txtRearTemperature.setText(
                                            String.valueOf(formattedTemperature) + " " + temperatureUnit);
                                    txtRearVoltage.setText(String.format("%.2f", voltage) + " V");
                                }
                                // Update txtOutput box and send notification
                                if ((frontStatus == 0) && (rearStatus == 0)) {
                                    txtOutput.setText("");
                                    if (notificationManager != null) {
                                        notificationManager.cancel(0);
                                    }
                                } else if ((frontStatus == 1) && (rearStatus == 0)) {
                                    txtOutput
                                            .setText(getResources().getString(R.string.alert_lowFrontPressure));
                                    Notify(getResources().getString(R.string.alert_lowFrontPressure));
                                } else if ((frontStatus == 2) && (rearStatus == 0)) {
                                    txtOutput.setText(
                                            getResources().getString(R.string.alert_highFrontPressure));
                                    Notify(getResources().getString(R.string.alert_highFrontPressure));
                                } else if ((rearStatus == 1) && (frontStatus == 0)) {
                                    txtOutput.setText(getResources().getString(R.string.alert_lowRearPressure));
                                    Notify(getResources().getString(R.string.alert_lowRearPressure));
                                } else if ((rearStatus == 2) && (frontStatus == 0)) {
                                    txtOutput
                                            .setText(getResources().getString(R.string.alert_highRearPressure));
                                    Notify(getResources().getString(R.string.alert_highRearPressure));
                                } else if ((frontStatus == 1) && (rearStatus == 1)) {
                                    txtOutput.setText(
                                            getResources().getString(R.string.alert_lowFrontLowRearPressure));
                                    Notify(getResources().getString(R.string.alert_lowFrontLowRearPressure));
                                } else if ((frontStatus == 2) && (rearStatus == 2)) {
                                    txtOutput.setText(
                                            getResources().getString(R.string.alert_highFrontHighRearPressure));
                                    Notify(getResources().getString(R.string.alert_highFrontHighRearPressure));
                                } else if ((frontStatus == 1) && (rearStatus == 2)) {
                                    txtOutput.setText(
                                            getResources().getString(R.string.alert_lowFrontHighRearPressure));
                                    Notify(getResources().getString(R.string.alert_lowFrontHighRearPressure));
                                } else if ((frontStatus == 2) && (rearStatus == 1)) {
                                    txtOutput.setText(
                                            getResources().getString(R.string.alert_highFrontLowRearPressure));
                                    Notify(getResources().getString(R.string.alert_highFrontLowRearPressure));
                                }
                                // Update color scheme
                                if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                    if (frontStatus == 0) {
                                        layoutFront.setBackground(background);
                                    } else {
                                        layoutFront.setBackground(redBackground);
                                    }
                                    if (rearStatus == 0) {
                                        layoutRear.setBackground(background);
                                    } else {
                                        layoutRear.setBackground(redBackground);
                                    }
                                    root.setBackgroundColor(getResources().getColor(android.R.color.white));
                                    txtOutput.setBackground(txtOutBackground);
                                    txtOutput.setTextColor(getResources().getColor(android.R.color.black));
                                    txtFrontPressure
                                            .setTextColor(getResources().getColor(android.R.color.black));
                                    txtFrontTemperature
                                            .setTextColor(getResources().getColor(android.R.color.black));
                                    txtFrontVoltage
                                            .setTextColor(getResources().getColor(android.R.color.black));
                                    txtRearPressure
                                            .setTextColor(getResources().getColor(android.R.color.black));
                                    txtRearTemperature
                                            .setTextColor(getResources().getColor(android.R.color.black));
                                    txtRearVoltage.setTextColor(getResources().getColor(android.R.color.black));
                                } else {
                                    if (frontStatus == 0) {
                                        layoutFront.setBackground(backgroundDark);
                                    } else {
                                        layoutFront.setBackground(redBackgroundDark);
                                    }
                                    if (rearStatus == 0) {
                                        layoutRear.setBackground(backgroundDark);
                                    } else {
                                        layoutRear.setBackground(redBackgroundDark);
                                    }
                                    root.setBackgroundColor(getResources().getColor(android.R.color.black));
                                    txtOutput.setBackground(txtOutBackgroundDark);
                                    txtOutput.setTextColor(getResources().getColor(android.R.color.white));
                                    txtFrontPressure
                                            .setTextColor(getResources().getColor(android.R.color.white));
                                    txtFrontTemperature
                                            .setTextColor(getResources().getColor(android.R.color.white));
                                    txtFrontVoltage
                                            .setTextColor(getResources().getColor(android.R.color.white));
                                    txtRearPressure
                                            .setTextColor(getResources().getColor(android.R.color.white));
                                    txtRearTemperature
                                            .setTextColor(getResources().getColor(android.R.color.white));
                                    txtRearVoltage.setTextColor(getResources().getColor(android.R.color.white));
                                }
                            } catch (NumberFormatException e) {
                                Log.d(TAG, "Malformed message, unexpected value");
                            }
                        }
                    }
                } else {
                    Log.d(TAG, "Malformed message, message length: " + msg.arg1);
                }
                break;
            }
        }
    };
    // Light Sensor Stuff
    SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    Sensor lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);

    if (lightSensor == null) {
        Log.d(TAG, "Light sensor not found");
    } else {
        float max = lightSensor.getMaximumRange();
        sensorManager.registerListener(lightSensorEventListener, lightSensor,
                SensorManager.SENSOR_DELAY_NORMAL);
        hasSensor = true;
        Log.d(TAG, "Light Sensor Max Value: " + max);
    }
    // Try to connect to iTPMSystem
    btConnect();
}