List of usage examples for android.hardware Sensor TYPE_LIGHT
int TYPE_LIGHT
To view the source code for android.hardware Sensor TYPE_LIGHT.
Click Source Link
From source file:com.vonglasow.michael.satstat.ui.MainActivity.java
/** * Called when a sensor's reading changes. Updates sensor display and rotates sky plot according * to bearing./*from w ww.j a v a 2s. c o m*/ */ public void onSensorChanged(SensorEvent event) { //to enforce sensor rate boolean isRateElapsed = false; switch (event.sensor.getType()) { case Sensor.TYPE_ACCELEROMETER: isRateElapsed = (event.timestamp / 1000) - mAccLast >= iSensorRate; // if Z acceleration is greater than X/Y combined, lock rotation, else unlock if (Math.pow(event.values[2], 2) > Math.pow(event.values[0], 2) + Math.pow(event.values[1], 2)) { // workaround (SCREEN_ORIENTATION_LOCK is unsupported on API < 18) if (isWideScreen) setRequestedOrientation( OR_FROM_ROT_WIDE[this.getWindowManager().getDefaultDisplay().getRotation()]); else setRequestedOrientation( OR_FROM_ROT_TALL[this.getWindowManager().getDefaultDisplay().getRotation()]); } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); } break; case Sensor.TYPE_ORIENTATION: isRateElapsed = (event.timestamp / 1000) - mOrLast >= iSensorRate; break; case Sensor.TYPE_GYROSCOPE: isRateElapsed = (event.timestamp / 1000) - mGyroLast >= iSensorRate; break; case Sensor.TYPE_MAGNETIC_FIELD: isRateElapsed = (event.timestamp / 1000) - mMagLast >= iSensorRate; break; case Sensor.TYPE_LIGHT: isRateElapsed = (event.timestamp / 1000) - mLightLast >= iSensorRate; break; case Sensor.TYPE_PROXIMITY: isRateElapsed = (event.timestamp / 1000) - mProximityLast >= iSensorRate; break; case Sensor.TYPE_PRESSURE: isRateElapsed = (event.timestamp / 1000) - mPressureLast >= iSensorRate; break; case Sensor.TYPE_RELATIVE_HUMIDITY: isRateElapsed = (event.timestamp / 1000) - mHumidityLast >= iSensorRate; break; case Sensor.TYPE_AMBIENT_TEMPERATURE: isRateElapsed = (event.timestamp / 1000) - mTempLast >= iSensorRate; break; } if (!isRateElapsed) return; switch (event.sensor.getType()) { case Sensor.TYPE_ACCELEROMETER: mAccLast = event.timestamp / 1000; break; case Sensor.TYPE_ORIENTATION: mOrLast = event.timestamp / 1000; break; case Sensor.TYPE_GYROSCOPE: mGyroLast = event.timestamp / 1000; break; case Sensor.TYPE_MAGNETIC_FIELD: mMagLast = event.timestamp / 1000; break; case Sensor.TYPE_LIGHT: mLightLast = event.timestamp / 1000; break; case Sensor.TYPE_PROXIMITY: mProximityLast = event.timestamp / 1000; break; case Sensor.TYPE_PRESSURE: mPressureLast = event.timestamp / 1000; break; case Sensor.TYPE_RELATIVE_HUMIDITY: mHumidityLast = event.timestamp / 1000; break; case Sensor.TYPE_AMBIENT_TEMPERATURE: mTempLast = event.timestamp / 1000; break; } if (sensorSectionFragment != null) { sensorSectionFragment.onSensorChanged(event); } if (gpsSectionFragment != null) { gpsSectionFragment.onSensorChanged(event); } }
From source file:com.vonglasow.michael.satstat.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); defaultUEH = Thread.getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { public void uncaughtException(Thread t, Throwable e) { Context c = getApplicationContext(); File dumpDir = c.getExternalFilesDir(null); File dumpFile = new File(dumpDir, "satstat-" + System.currentTimeMillis() + ".log"); PrintStream s;/*from w ww. ja v a 2s .c om*/ try { InputStream buildInStream = getResources().openRawResource(R.raw.build); s = new PrintStream(dumpFile); s.append("SatStat build: "); int i; try { i = buildInStream.read(); while (i != -1) { s.write(i); i = buildInStream.read(); } buildInStream.close(); } catch (IOException e1) { e1.printStackTrace(); } s.append("\n\n"); e.printStackTrace(s); s.flush(); s.close(); } catch (FileNotFoundException e2) { e2.printStackTrace(); } defaultUEH.uncaughtException(t, e); } }); mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); mSharedPreferences.registerOnSharedPreferenceChangeListener(this); final ActionBar actionBar = getActionBar(); setContentView(R.layout.activity_main); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // Find out default screen orientation Configuration config = getResources().getConfiguration(); WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE); int rot = wm.getDefaultDisplay().getRotation(); isWideScreen = (config.orientation == Configuration.ORIENTATION_LANDSCAPE && (rot == Surface.ROTATION_0 || rot == Surface.ROTATION_180) || config.orientation == Configuration.ORIENTATION_PORTRAIT && (rot == Surface.ROTATION_90 || rot == Surface.ROTATION_270)); Log.d("MainActivity", "isWideScreen=" + Boolean.toString(isWideScreen)); // compact action bar int dpX = (int) (this.getResources().getDisplayMetrics().widthPixels / this.getResources().getDisplayMetrics().density); /* * This is a crude way to ensure a one-line action bar with tabs * (not a drop-down list) and home (incon) and title only if there * is space, depending on screen width: * divide screen in units of 64 dp * each tab requires 1 unit, home and menu require slightly less, * title takes up approx. 2.5 units in portrait, * home and title are about 2 units wide in landscape */ if (dpX < 192) { // just enough space for drop-down list and menu actionBar.setDisplayShowHomeEnabled(false); actionBar.setDisplayShowTitleEnabled(false); } else if (dpX < 320) { // not enough space for four tabs, but home will fit next to list actionBar.setDisplayShowHomeEnabled(true); actionBar.setDisplayShowTitleEnabled(false); } else if (dpX < 384) { // just enough space for four tabs actionBar.setDisplayShowHomeEnabled(false); actionBar.setDisplayShowTitleEnabled(false); } else if ((dpX < 448) || ((config.orientation == Configuration.ORIENTATION_PORTRAIT) && (dpX < 544))) { // space for four tabs and home, but not title actionBar.setDisplayShowHomeEnabled(true); actionBar.setDisplayShowTitleEnabled(false); } else { // ample space for home, title and all four tabs actionBar.setDisplayShowHomeEnabled(true); actionBar.setDisplayShowTitleEnabled(true); } setEmbeddedTabs(actionBar, true); providerLocations = new HashMap<String, Location>(); mAvailableProviderStyles = new ArrayList<String>(Arrays.asList(LOCATION_PROVIDER_STYLES)); providerStyles = new HashMap<String, String>(); providerAppliedStyles = new HashMap<String, String>(); providerInvalidationHandler = new Handler(); providerInvalidators = new HashMap<String, Runnable>(); // Create the adapter that will return a fragment for each of the three // primary sections of the app. mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); // Set up the ViewPager with the sections adapter. mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mSectionsPagerAdapter); mViewPager.setOnPageChangeListener(this); // Add tabs, specifying the tab's text and TabListener for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { actionBar.addTab(actionBar.newTab() //.setText(mSectionsPagerAdapter.getPageTitle(i)) .setIcon(mSectionsPagerAdapter.getPageIcon(i)).setTabListener(this)); } // This is needed by the mapsforge library. AndroidGraphicFactory.createInstance(this.getApplication()); // Get system services for event delivery mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mOrSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); mAccSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mGyroSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE); mMagSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY); mPressureSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE); mHumiditySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_RELATIVE_HUMIDITY); mTempSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE); mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); mAccSensorRes = getSensorDecimals(mAccSensor, mAccSensorRes); mGyroSensorRes = getSensorDecimals(mGyroSensor, mGyroSensorRes); mMagSensorRes = getSensorDecimals(mMagSensor, mMagSensorRes); mLightSensorRes = getSensorDecimals(mLightSensor, mLightSensorRes); mProximitySensorRes = getSensorDecimals(mProximitySensor, mProximitySensorRes); mPressureSensorRes = getSensorDecimals(mPressureSensor, mPressureSensorRes); mHumiditySensorRes = getSensorDecimals(mHumiditySensor, mHumiditySensorRes); mTempSensorRes = getSensorDecimals(mTempSensor, mTempSensorRes); networkTimehandler = new Handler(); networkTimeRunnable = new Runnable() { @Override public void run() { int newNetworkType = mTelephonyManager.getNetworkType(); if (getNetworkGeneration(newNetworkType) != mLastNetworkGen) onNetworkTypeChanged(newNetworkType); else networkTimehandler.postDelayed(this, NETWORK_REFRESH_DELAY); } }; wifiTimehandler = new Handler(); wifiTimeRunnable = new Runnable() { @Override public void run() { mWifiManager.startScan(); wifiTimehandler.postDelayed(this, WIFI_REFRESH_DELAY); } }; updateLocationProviderStyles(); }
From source file:org.thecongers.mcluster.MainActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Keep screen on getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.activity_main); setTitle(R.string.app_name);// ww w.java 2 s . co m View myView = findViewById(R.id.layoutApp); root = myView.getRootView(); layoutIcons = (LinearLayout) findViewById(R.id.layoutIcons); layoutMiddleLeft = (LinearLayout) findViewById(R.id.layoutMiddleLeft); layoutMiddleRight = (LinearLayout) findViewById(R.id.layoutMiddleRight); layoutBottomLeft = (LinearLayout) findViewById(R.id.layoutBottomLeft); layoutBottomRight = (LinearLayout) findViewById(R.id.layoutBottomRight); imageKillSwitch = (ImageView) findViewById(R.id.imageViewKillSwitch); imageLeftArrow = (ImageView) findViewById(R.id.imageViewLeftArrow); imageRightArrow = (ImageView) findViewById(R.id.imageViewRightArrow); imageHighBeam = (ImageView) findViewById(R.id.imageViewHighBeam); imageHeatedGrips = (ImageView) findViewById(R.id.imageViewHeatedGrips); imageABS = (ImageView) findViewById(R.id.imageViewABS); imageLampf = (ImageView) findViewById(R.id.imageViewLampf); imageFuelWarning = (ImageView) findViewById(R.id.imageViewFuelWarning); imageFuelLevel = (ImageView) findViewById(R.id.imageViewFuelLevel); imageESA = (ImageView) findViewById(R.id.imageViewESA); txtSpeed = (TextView) findViewById(R.id.textViewSpeed); txtSpeedUnit = (TextView) findViewById(R.id.textViewSpeedUnit); txtGear = (TextView) findViewById(R.id.textViewGear); txtOdometers = (TextView) findViewById(R.id.textViewOdometer); txtESA = (TextView) findViewById(R.id.textViewESA); imageButtonTPMS = (ImageButton) findViewById(R.id.imageButtonTPMS); imageButtonBluetooth = (ImageButton) findViewById(R.id.imageButtonBluetooth); imageButtonPreference = (ImageButton) findViewById(R.id.imageButtonPreference); progressFuelLevel = (ProgressBar) findViewById(R.id.progressBarFuelLevel); // Backgrounds background = R.drawable.rectangle_bordered; backgroundDark = R.drawable.rectangle_bordered_dark; sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); // Update layout updateLayout(); if (!sharedPrefs.getBoolean("prefEnableTPMS", false)) { imageButtonTPMS.setImageResource(R.mipmap.blank_icon); imageButtonTPMS.setEnabled(false); } else { imageButtonTPMS.setImageResource(R.mipmap.tpms_off); imageButtonTPMS.setEnabled(true); } // Set initial color scheme updateColors(); if (sharedPrefs.getBoolean("prefNightMode", false)) { imageHeatedGrips.setImageResource(R.mipmap.heated_grips_high_dark); } // 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); // Setup Text To Speech text2speech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { if (status != TextToSpeech.ERROR) { text2speech.setLanguage(Locale.US); } } }); imageButtonBluetooth.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { canBusConnect(); } }); imageButtonTPMS.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (sharedPrefs.getBoolean("prefEnableTPMS", false)) { iTPMSConnect(); } } }); imageButtonPreference.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { PopupMenu popup = new PopupMenu(MainActivity.this, v); popup.getMenuInflater().inflate(R.menu.main, popup.getMenu()); popup.setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: // Settings Menu was selected Intent i = new Intent(getApplicationContext(), org.thecongers.mcluster.UserSettingActivity.class); startActivityForResult(i, SETTINGS_RESULT); return true; case R.id.action_about: // About was selected AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle(getResources().getString(R.string.alert_about_title)); builder.setMessage(readRawTextFile(MainActivity.this, R.raw.about)); builder.setPositiveButton(getResources().getString(R.string.alert_about_button), null); builder.show(); return true; case R.id.action_exit: // Exit menu item was selected if (logger != null) { logger.shutdown(); } finish(); System.exit(0); default: return true; } } }); popup.show(); } }); layoutMiddleRight.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int infoViewCurr = Integer.valueOf(sharedPrefs.getString("prefInfoView", "0")); if (infoViewCurr < (numInfoViewLayouts - 1)) { infoViewCurr = infoViewCurr + 1; } else { infoViewCurr = 0; } SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putString("prefInfoView", String.valueOf(infoViewCurr)); editor.commit(); //update layout updateLayout(); } }); canBusMessages = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case RECEIVE_MESSAGE: // Check to see if message is the correct size if (msg.arg1 == 27) { byte[] readBuf = (byte[]) msg.obj; String message = new String(readBuf); //Default Units String speedUnit = "km/h"; String odometerUnit = "km"; String temperatureUnit = "C"; String[] splitMessage = message.split(","); if (splitMessage[0].contains("10C")) { //RPM if (sharedPrefs.getString("prefInfoView", "0").contains("0")) { int rpm = (Integer.parseInt(splitMessage[4], 16) * 255 + Integer.parseInt(splitMessage[3], 16)) / 4; txtInfo = (TextView) findViewById(R.id.textViewInfo); txtInfo.setGravity(Gravity.CENTER | Gravity.BOTTOM); txtInfo.setTextSize(TypedValue.COMPLEX_UNIT_SP, 40); txtInfo.setText(Integer.toString(rpm) + " RPM"); if (rpm > 8500) { txtInfo.setTextColor(getResources().getColor(R.color.red)); } else { txtInfo.setTextColor(getResources().getColor(android.R.color.black)); } } //Kill Switch String killSwitchValue = splitMessage[5].substring(1); if (killSwitchValue.contains("5") || killSwitchValue.contains("9")) { //Kill Switch On imageKillSwitch.setImageResource(R.mipmap.kill_switch); } else { //Kill Switch Off imageKillSwitch.setImageResource(R.mipmap.blank_icon); } } else if (splitMessage[0].contains("130")) { //Turn indicators String indicatorValue = splitMessage[8]; if (indicatorValue.contains("D7")) { imageLeftArrow.setImageResource(R.mipmap.left_arrow); imageRightArrow.setImageResource(R.mipmap.blank_icon); } else if (indicatorValue.contains("E7")) { imageLeftArrow.setImageResource(R.mipmap.blank_icon); imageRightArrow.setImageResource(R.mipmap.right_arrow); } else if (indicatorValue.contains("EF")) { imageLeftArrow.setImageResource(R.mipmap.left_arrow); imageRightArrow.setImageResource(R.mipmap.right_arrow); } else { imageLeftArrow.setImageResource(R.mipmap.blank_icon); imageRightArrow.setImageResource(R.mipmap.blank_icon); } //High Beam String highBeamValue = splitMessage[7].substring(1); if (highBeamValue.contains("9")) { //High Beam On imageHighBeam.setImageResource(R.mipmap.high_beam); } else { //High Beam Off imageHighBeam.setImageResource(R.mipmap.blank_icon); } } else if (splitMessage[0].contains("294")) { //Front Wheel Speed double frontSpeed = ((Integer.parseInt(splitMessage[4], 16) * 256.0 + Integer.parseInt(splitMessage[3], 16)) * 0.063); //If 21" Wheel if (sharedPrefs.getString("prefDistance", "0").contains("1")) { frontSpeed = ((Integer.parseInt(splitMessage[4], 16) * 256.0 + Integer.parseInt(splitMessage[3], 16)) * 0.064); } if (sharedPrefs.getString("prefDistance", "0").contains("0")) { speedUnit = "MPH"; frontSpeed = frontSpeed / 1.609344; } txtSpeed.setText(String.valueOf((int) Math.round(frontSpeed))); txtSpeedUnit.setText(speedUnit); //ABS String absValue = splitMessage[2].substring(0, 1); if (absValue.contains("B")) { //ABS Off imageABS.setImageResource(R.mipmap.abs); } else { //ABS On imageABS.setImageResource(R.mipmap.blank_icon); } } else if (splitMessage[0].contains("2BC")) { //Engine Temperature engineTempC = (Integer.parseInt(splitMessage[3], 16) * 0.75) - 24.0; if (engineTempC >= 115.5) { if (engineTempAlertTriggered == false) { engineTempAlertTriggered = true; speakString(getResources().getString(R.string.engine_temp_alert)); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putString("prefInfoView", String.valueOf(3)); editor.commit(); updateLayout(); } } else { engineTempAlertTriggered = false; } if (sharedPrefs.getString("prefInfoView", "0").contains("3")) { double engineTemp = engineTempC; if (sharedPrefs.getString("prefTempF", "0").contains("1")) { // F engineTemp = (int) Math.round((9.0 / 5.0) * engineTemp + 32.0); temperatureUnit = "F"; } txtEngineTemp.setText(String.valueOf(engineTemp) + temperatureUnit); } // Gear String gearValue = splitMessage[6].substring(0, 1); String gear; if (gearValue.contains("1")) { gear = "1"; } else if (gearValue.contains("2")) { gear = "N"; } else if (gearValue.contains("4")) { gear = "2"; } else if (gearValue.contains("7")) { gear = "3"; } else if (gearValue.contains("8")) { gear = "4"; } else if (gearValue.contains("B")) { gear = "5"; } else if (gearValue.contains("D")) { gear = "6"; } else { gear = "-"; } txtGear.setText(gear); //Air Temperature airTempC = (Integer.parseInt(splitMessage[8], 16) * 0.75) - 48.0; //Freeze Warning if (airTempC <= 0.0) { if (freezeAlertTriggered == false) { freezeAlertTriggered = true; speakString(getResources().getString(R.string.freeze_alert)); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putString("prefInfoView", String.valueOf(3)); editor.commit(); updateLayout(); } } else { freezeAlertTriggered = false; } if (sharedPrefs.getString("prefInfoView", "0").contains("3")) { double airTemp = airTempC; if (sharedPrefs.getString("prefTempF", "0").contains("1")) { // F airTemp = (int) Math.round((9.0 / 5.0) * airTemp + 32.0); temperatureUnit = "F"; } txtAirTemp.setText(String.valueOf(airTemp) + temperatureUnit); } } else if (splitMessage[0].contains("2D0")) { //Info Button String infoButtonValue = splitMessage[6].substring(1); if (infoButtonValue.contains("5")) { //Short Press if (!btnPressed) { int infoButton = Integer.valueOf(sharedPrefs.getString("prefInfoView", "0")); if (infoButton < (numInfoViewLayouts - 1)) { infoButton = infoButton + 1; } else { infoButton = 0; } SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putString("prefInfoView", String.valueOf(infoButton)); editor.commit(); //update layout updateLayout(); btnPressed = true; } } else if (infoButtonValue.contains("6")) { //Long Press } else { btnPressed = false; } //Heated Grips String heatedGripSwitchValue = splitMessage[8].substring(0, 1); if (heatedGripSwitchValue.contains("C")) { imageHeatedGrips.setImageResource(R.mipmap.blank_icon); } else if (heatedGripSwitchValue.contains("D")) { if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageHeatedGrips.setImageResource(R.mipmap.heated_grips_low); } else { imageHeatedGrips.setImageResource(R.mipmap.heated_grips_low_dark); } } else if (heatedGripSwitchValue.contains("E")) { if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageHeatedGrips.setImageResource(R.mipmap.heated_grips_high); } else { imageHeatedGrips.setImageResource(R.mipmap.heated_grips_high_dark); } } else { imageHeatedGrips.setImageResource(R.mipmap.blank_icon); } //ESA Damping and Preload String esaDampingValue1 = splitMessage[5].substring(1); String esaDampingValue2 = splitMessage[8].substring(1); String esaPreLoadValue = splitMessage[5].substring(0, 1); if (esaDampingValue1.contains("B") && esaDampingValue2.contains("1")) { txtESA.setText("SOFT"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.smooth_terrain); } else { imageESA.setImageResource(R.mipmap.smooth_terrain_dark); } } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("2")) { txtESA.setText("NORM"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.smooth_terrain); } else { imageESA.setImageResource(R.mipmap.smooth_terrain_dark); } } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("3")) { txtESA.setText("HARD"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.smooth_terrain); } else { imageESA.setImageResource(R.mipmap.smooth_terrain_dark); } } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("4")) { txtESA.setText("SOFT"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.uneven_terrain); } else { imageESA.setImageResource(R.mipmap.uneven_terrain_dark); } } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("5")) { txtESA.setText("NORM"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.uneven_terrain); } else { imageESA.setImageResource(R.mipmap.uneven_terrain_dark); } } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("6")) { txtESA.setText("HARD"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.uneven_terrain); } else { imageESA.setImageResource(R.mipmap.uneven_terrain_dark); } } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("1")) { txtESA.setText("SOFT"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.smooth_terrain); } else { imageESA.setImageResource(R.mipmap.smooth_terrain_dark); } } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("2")) { txtESA.setText("NORM"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.smooth_terrain); } else { imageESA.setImageResource(R.mipmap.smooth_terrain_dark); } } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("3")) { txtESA.setText("HARD"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.smooth_terrain); } else { imageESA.setImageResource(R.mipmap.smooth_terrain_dark); } } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("4")) { txtESA.setText("SOFT"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.uneven_terrain); } else { imageESA.setImageResource(R.mipmap.uneven_terrain_dark); } } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("5")) { txtESA.setText("NORM"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.uneven_terrain); } else { imageESA.setImageResource(R.mipmap.uneven_terrain_dark); } } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("6")) { txtESA.setText("HARD"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.uneven_terrain); } else { imageESA.setImageResource(R.mipmap.uneven_terrain_dark); } } else if (esaPreLoadValue.contains("1")) { txtESA.setText("COMF"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.helmet); } else { imageESA.setImageResource(R.mipmap.helmet_dark); } } else if (esaPreLoadValue.contains("2")) { txtESA.setText("NORM"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.helmet); } else { imageESA.setImageResource(R.mipmap.helmet_dark); } } else if (esaPreLoadValue.contains("3")) { txtESA.setText("SPORT"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.helmet); } else { imageESA.setImageResource(R.mipmap.helmet_dark); } } else if (esaPreLoadValue.contains("4")) { txtESA.setText("COMF"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.helmet_luggage); } else { imageESA.setImageResource(R.mipmap.helmet_luggage_dark); } } else if (esaPreLoadValue.contains("5")) { txtESA.setText("NORM"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.helmet_luggage); } else { imageESA.setImageResource(R.mipmap.helmet_luggage_dark); } } else if (esaPreLoadValue.contains("6")) { txtESA.setText("SPORT"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.helmet_luggage); } else { imageESA.setImageResource(R.mipmap.helmet_luggage_dark); } } else if (esaPreLoadValue.contains("7")) { txtESA.setText("COMF"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.helmet_helmet); } else { imageESA.setImageResource(R.mipmap.helmet_helmet_dark); } } else if (esaPreLoadValue.contains("8")) { txtESA.setText("NORM"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.helmet_helmet); } else { imageESA.setImageResource(R.mipmap.helmet_helmet_dark); } } else if (esaPreLoadValue.contains("9")) { txtESA.setText("SPORT"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.helmet_helmet); } else { imageESA.setImageResource(R.mipmap.helmet_helmet_dark); } } else { txtESA.setText(""); imageESA.setImageResource(R.mipmap.blank_icon); } //Lamp Fault //TODO: Display/speak Bulb location String lampFaultValue = splitMessage[3].substring(0, 1); if (lampFaultValue.contains("0")) { //None imageLampf.setImageResource(R.mipmap.blank_icon); } else if (lampFaultValue.contains("1")) { //Low Beam imageLampf.setImageResource(R.mipmap.lampf); } else if (lampFaultValue.contains("4")) { //High Beam imageLampf.setImageResource(R.mipmap.lampf); } else if (lampFaultValue.contains("8")) { //Signal Bulb imageLampf.setImageResource(R.mipmap.lampf); } else { //Unknown imageLampf.setImageResource(R.mipmap.lampf); } //Fuel Level double fuelLevelPercent = ((Integer.parseInt(splitMessage[4], 16) - 73) / 182.0) * 100.0; progressFuelLevel.setProgress((int) Math.round(fuelLevelPercent)); //Fuel Level Warning double fuelWarning = sharedPrefs.getInt("prefFuelWarning", 30); if (fuelLevelPercent >= fuelWarning) { imageFuelWarning.setImageResource(R.mipmap.blank_icon); fuelAlertTriggered = false; fuelReserveAlertTriggered = false; } else if (fuelLevelPercent == 0) { //Visual Warning imageFuelWarning.setImageResource(R.mipmap.fuel_warning); if (!fuelReserveAlertTriggered) { fuelReserveAlertTriggered = true; //Audio Warning speakString(getResources().getString(R.string.fuel_alert_reserve)); } } else { //Visual Warning imageFuelWarning.setImageResource(R.mipmap.fuel_warning); if (!fuelAlertTriggered) { fuelAlertTriggered = true; //Audio Warning String fuelAlert = getResources().getString(R.string.fuel_alert_begin) + String.valueOf((int) Math.round(fuelLevelPercent)) + getResources().getString(R.string.fuel_alert_end); speakString(fuelAlert); //Suggest nearby fuel stations if (!sharedPrefs.getString("prefFuelStation", "0").contains("0")) { // Display prompt to open google maps MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { AlertDialog.Builder builder = new AlertDialog.Builder( MainActivity.this); builder.setTitle(getResources() .getString(R.string.alert_fuel_stations_title)); if (sharedPrefs.getString("prefFuelStation", "0").contains("1")) { // Search for fuel stations nearby builder.setMessage(getResources().getString( R.string.alert_fuel_stations_message_suggestions)); } else if (sharedPrefs.getString("prefFuelStation", "0") .contains("2")) { // Route to nearest fuel station builder.setMessage(getResources().getString( R.string.alert_fuel_stations_message_navigation)); } builder.setPositiveButton( getResources().getString( R.string.alert_fuel_stations_button_positive), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Uri gmmIntentUri = null; if (sharedPrefs.getString("prefFuelStation", "0") .contains("1")) { // Search for fuel stations nearby gmmIntentUri = Uri .parse("geo:0,0?q=gas+station"); } else if (sharedPrefs .getString("prefFuelStation", "0") .contains("2")) { // Route to nearest fuel station gmmIntentUri = Uri.parse( "google.navigation:q=gas+station"); } Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri); mapIntent .setPackage("com.google.android.apps.maps"); startActivity(mapIntent); } }); builder.setNegativeButton( getResources().getString( R.string.alert_fuel_stations_button_negative), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); builder.show(); } }); } } } } else if (splitMessage[0].contains("3F8")) { String odometerValue = ""; for (int i = 4; i > 1; i--) { odometerValue = odometerValue + splitMessage[i]; } double odometer = Integer.parseInt(odometerValue, 16); if (sharedPrefs.getString("prefDistance", "0").contains("0")) { odometerUnit = "Miles"; odometer = odometer * 0.6214; } txtOdometers.setText(String.valueOf((int) Math.round(odometer)) + " " + odometerUnit); } imageButtonBluetooth.setImageResource(R.mipmap.bluetooth_on); if (sharedPrefs.getBoolean("prefDataLogging", false)) { // Log data if (logger == null) { logger = new LogData(); } if (logger != null) { logger.write(message); } } } else { Log.d(TAG, "Malformed message, message length: " + msg.arg1); } break; } } }; sensorMessages = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case RECEIVE_MESSAGE: // Message received Log.d(TAG, "iTPMS 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]); // Only parse message if there is one or more sensor mappings String prefFrontID = sharedPrefs.getString("prefFrontID", ""); String prefRearID = sharedPrefs.getString("prefRearID", ""); 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 lowPressure = Integer.parseInt(sharedPrefs.getString("prefLowPressure", "30")); int highPressure = Integer .parseInt(sharedPrefs.getString("prefHighPressure", "46")); if (sharedPrefs.getString("prefTempF", "0").contains("1")) { // 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]; if (Integer.parseInt(hexData[3], 16) <= 2) { Log.d(TAG, "Front ID matched: " + Integer.parseInt(hexData[3], 16)); frontPressurePSI = psi; // Set front tire status if (psi <= lowPressure) { frontStatus = 1; } else if (psi >= highPressure) { frontStatus = 2; } else { frontStatus = 0; } if (sharedPrefs.getString("prefInfoView", "0").contains("2")) { txtFrontTPMS = (TextView) findViewById(R.id.textViewFrontTPMS); txtFrontTPMS.setTextSize(TypedValue.COMPLEX_UNIT_SP, 50); txtFrontTPMS .setText(String.valueOf(formattedPressure) + " " + pressureUnit); if (frontStatus != 0) { txtFrontTPMS.setTextColor(getResources().getColor(R.color.red)); } else { txtFrontTPMS .setTextColor(getResources().getColor(android.R.color.black)); } } } else if (Integer.parseInt(hexData[3], 16) > 2) { Log.d(TAG, "Rear ID matched: " + Integer.parseInt(hexData[3], 16)); rearPressurePSI = psi; // Set rear tire status if (psi <= lowPressure) { rearStatus = 4; } else if (psi >= highPressure) { rearStatus = 5; } else { rearStatus = 3; } if (sharedPrefs.getString("prefInfoView", "0").contains("2")) { txtRearTPMS = (TextView) findViewById(R.id.textViewRearTPMS); txtRearTPMS.setTextSize(TypedValue.COMPLEX_UNIT_SP, 50); txtRearTPMS.setText(String.valueOf(formattedPressure) + " " + pressureUnit); if (rearStatus != 3) { txtRearTPMS.setTextColor(getResources().getColor(R.color.red)); } else { txtRearTPMS .setTextColor(getResources().getColor(android.R.color.black)); } } } // Reset icon if ((frontStatus == 0) && (rearStatus == 3)) { imageButtonTPMS.setImageResource(R.mipmap.tpms_on); } if ((frontStatus != 0) || (rearStatus != 3)) { imageButtonTPMS.setImageResource(R.mipmap.tpms_alert); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putString("prefInfoView", String.valueOf(2)); editor.commit(); updateLayout(); int delay = (Integer .parseInt(sharedPrefs.getString("prefAudioAlertDelay", "30")) * 1000); String currStatus = (String.valueOf(frontStatus) + String.valueOf(rearStatus)); if (alertTimer == 0) { alertTimer = System.currentTimeMillis(); } else { long currentTime = System.currentTimeMillis(); long duration = (currentTime - alertTimer); if (!currStatus.equals(lastStatus) || duration >= delay) { alertTimer = 0; if ((frontStatus == 1) && (rearStatus == 3)) { speakString( getResources().getString(R.string.alert_lowFrontPressure)); } else if ((frontStatus == 2) && (rearStatus == 3)) { speakString( getResources().getString(R.string.alert_highFrontPressure)); } else if ((rearStatus == 4) && (frontStatus == 0)) { speakString( getResources().getString(R.string.alert_lowRearPressure)); } else if ((rearStatus == 5) && (frontStatus == 0)) { speakString( getResources().getString(R.string.alert_highRearPressure)); } else if ((frontStatus == 1) && (rearStatus == 4)) { speakString(getResources() .getString(R.string.alert_lowFrontLowRearPressure)); } else if ((frontStatus == 2) && (rearStatus == 5)) { speakString(getResources() .getString(R.string.alert_highFrontHighRearPressure)); } else if ((frontStatus == 1) && (rearStatus == 5)) { speakString(getResources() .getString(R.string.alert_lowFrontHighRearPressure)); } else if ((frontStatus == 2) && (rearStatus == 4)) { speakString(getResources() .getString(R.string.alert_highFrontLowRearPressure)); } lastStatus = (String.valueOf(frontStatus) + String.valueOf(rearStatus)); } } } } catch (NumberFormatException e) { Log.d(TAG, "Malformed message, unexpected value"); } if (sharedPrefs.getBoolean("prefDataLogging", false)) { // Log data if (logger == null) { logger = new LogData(); } if (logger != null) { logger.write(String.valueOf(sbhex)); } } } } else { Log.d(TAG, "Malformed message, message length: " + msg.arg1); } break; } } }; // Sensor Stuff SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); Sensor lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); Sensor accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); Sensor magnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); // Light if (lightSensor == null) { Log.d(TAG, "Light sensor not found"); } else { sensorManager.registerListener(sensorEventListener, lightSensor, SensorManager.SENSOR_DELAY_NORMAL); hasSensor = true; } // Compass sensorManager.registerListener(sensorEventListener, accelerometer, SensorManager.SENSOR_DELAY_UI); sensorManager.registerListener(sensorEventListener, magnetometer, SensorManager.SENSOR_DELAY_UI); // Try to connect to CANBusGateway canBusConnect(); // Connect to iTPMS if enabled if (sharedPrefs.getBoolean("prefEnableTPMS", false)) { iTPMSConnect(); } }
From source file:com.davidmascharka.lips.TrackerActivity.java
@Override public void onSensorChanged(SensorEvent event) { switch (event.sensor.getType()) { case Sensor.TYPE_ACCELEROMETER: accelerometerX = event.values[0]; accelerometerY = event.values[1]; accelerometerZ = event.values[2]; break;/* w w w . j a va 2 s . c om*/ case Sensor.TYPE_MAGNETIC_FIELD: magneticX = event.values[0]; magneticY = event.values[1]; magneticZ = event.values[2]; break; case Sensor.TYPE_LIGHT: light = event.values[0]; break; case Sensor.TYPE_ROTATION_VECTOR: rotationX = event.values[0]; rotationY = event.values[1]; rotationZ = event.values[2]; break; default: break; } SensorManager.getRotationMatrix(rotation, inclination, new float[] { accelerometerX, accelerometerY, accelerometerZ }, new float[] { magneticX, magneticY, magneticZ }); orientation = SensorManager.getOrientation(rotation, orientation); }
From source file:com.vonglasow.michael.satstat.MainActivity.java
/** * Called when a sensor's reading changes. Updates sensor display. *//* ww w.j a va2 s . c o m*/ public void onSensorChanged(SensorEvent event) { //to enforce sensor rate boolean isRateElapsed = false; switch (event.sensor.getType()) { case Sensor.TYPE_ACCELEROMETER: isRateElapsed = (event.timestamp / 1000) - mAccLast >= iSensorRate; // if Z acceleration is greater than X/Y combined, lock rotation, else unlock if (Math.pow(event.values[2], 2) > Math.pow(event.values[0], 2) + Math.pow(event.values[1], 2)) { // workaround (SCREEN_ORIENTATION_LOCK is unsupported on API < 18) if (isWideScreen) setRequestedOrientation( OR_FROM_ROT_WIDE[this.getWindowManager().getDefaultDisplay().getRotation()]); else setRequestedOrientation( OR_FROM_ROT_TALL[this.getWindowManager().getDefaultDisplay().getRotation()]); } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); } break; case Sensor.TYPE_ORIENTATION: isRateElapsed = (event.timestamp / 1000) - mOrLast >= iSensorRate; break; case Sensor.TYPE_GYROSCOPE: isRateElapsed = (event.timestamp / 1000) - mGyroLast >= iSensorRate; break; case Sensor.TYPE_MAGNETIC_FIELD: isRateElapsed = (event.timestamp / 1000) - mMagLast >= iSensorRate; break; case Sensor.TYPE_LIGHT: isRateElapsed = (event.timestamp / 1000) - mLightLast >= iSensorRate; break; case Sensor.TYPE_PROXIMITY: isRateElapsed = (event.timestamp / 1000) - mProximityLast >= iSensorRate; break; case Sensor.TYPE_PRESSURE: isRateElapsed = (event.timestamp / 1000) - mPressureLast >= iSensorRate; break; case Sensor.TYPE_RELATIVE_HUMIDITY: isRateElapsed = (event.timestamp / 1000) - mHumidityLast >= iSensorRate; break; case Sensor.TYPE_AMBIENT_TEMPERATURE: isRateElapsed = (event.timestamp / 1000) - mTempLast >= iSensorRate; break; } if (isSensorViewReady && isRateElapsed) { switch (event.sensor.getType()) { case Sensor.TYPE_ACCELEROMETER: mAccLast = event.timestamp / 1000; accX.setText(String.format("%." + mAccSensorRes + "f", event.values[0])); accY.setText(String.format("%." + mAccSensorRes + "f", event.values[1])); accZ.setText(String.format("%." + mAccSensorRes + "f", event.values[2])); accTotal.setText(String.format("%." + mAccSensorRes + "f", Math.sqrt(Math.pow(event.values[0], 2) + Math.pow(event.values[1], 2) + Math.pow(event.values[2], 2)))); accStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy))); break; case Sensor.TYPE_ORIENTATION: mOrLast = event.timestamp / 1000; orAzimuth.setText(String.format("%.0f%s", event.values[0], getString(R.string.unit_degree))); orAziText.setText(formatOrientation(event.values[0])); orPitch.setText(String.format("%.0f%s", event.values[1], getString(R.string.unit_degree))); orRoll.setText(String.format("%.0f%s", event.values[2], getString(R.string.unit_degree))); orStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy))); break; case Sensor.TYPE_GYROSCOPE: mGyroLast = event.timestamp / 1000; rotX.setText(String.format("%." + mGyroSensorRes + "f", event.values[0])); rotY.setText(String.format("%." + mGyroSensorRes + "f", event.values[1])); rotZ.setText(String.format("%." + mGyroSensorRes + "f", event.values[2])); rotTotal.setText(String.format("%." + mGyroSensorRes + "f", Math.sqrt(Math.pow(event.values[0], 2) + Math.pow(event.values[1], 2) + Math.pow(event.values[2], 2)))); rotStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy))); break; case Sensor.TYPE_MAGNETIC_FIELD: mMagLast = event.timestamp / 1000; magX.setText(String.format("%." + mMagSensorRes + "f", event.values[0])); magY.setText(String.format("%." + mMagSensorRes + "f", event.values[1])); magZ.setText(String.format("%." + mMagSensorRes + "f", event.values[2])); magTotal.setText(String.format("%." + mMagSensorRes + "f", Math.sqrt(Math.pow(event.values[0], 2) + Math.pow(event.values[1], 2) + Math.pow(event.values[2], 2)))); magStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy))); break; case Sensor.TYPE_LIGHT: mLightLast = event.timestamp / 1000; light.setText(String.format("%." + mLightSensorRes + "f", event.values[0])); lightStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy))); break; case Sensor.TYPE_PROXIMITY: mProximityLast = event.timestamp / 1000; proximity.setText(String.format("%." + mProximitySensorRes + "f", event.values[0])); proximityStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy))); break; case Sensor.TYPE_PRESSURE: mPressureLast = event.timestamp / 1000; metPressure.setText(String.format("%." + mPressureSensorRes + "f", event.values[0])); pressureStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy))); break; case Sensor.TYPE_RELATIVE_HUMIDITY: mHumidityLast = event.timestamp / 1000; metHumid.setText(String.format("%." + mHumiditySensorRes + "f", event.values[0])); humidStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy))); break; case Sensor.TYPE_AMBIENT_TEMPERATURE: mTempLast = event.timestamp / 1000; metTemp.setText(String.format("%." + mTempSensorRes + "f", event.values[0])); tempStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy))); break; } } if (isGpsViewReady && isRateElapsed) { switch (event.sensor.getType()) { case Sensor.TYPE_ORIENTATION: gpsStatusView.setYaw(event.values[0]); break; } } }
From source file:com.example.sensingapp.SensingApp.java
private void UpdateSensorServiceRegistration() { //Register sensors according to the enable/disable status // if (m_blnAcclEnabled) { // m_smSurScan.registerListener(m_actHome, m_smSurScan.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION), m_nAcclMode); // m_smSurScan.registerListener(m_actHome, m_smSurScan.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), m_nAcclMode); // } else { // m_smSurScan.unregisterListener(m_actHome, m_smSurScan.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION)); // m_smSurScan.unregisterListener(m_actHome, m_smSurScan.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)); // }//from w w w. j a v a 2 s .c o m if (m_blnAcclEnabled) { m_smSurScan.registerListener(m_actHome, m_smSurScan.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), m_nAcclMode); } else { m_smSurScan.unregisterListener(m_actHome, m_smSurScan.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)); } if (m_blnLinearAcclEnabled) { m_smSurScan.registerListener(m_actHome, m_smSurScan.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION), m_nLinearAcclMode); } else { m_smSurScan.unregisterListener(m_actHome, m_smSurScan.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION)); } if (m_blnGravityEnabled) { m_smSurScan.registerListener(m_actHome, m_smSurScan.getDefaultSensor(Sensor.TYPE_GRAVITY), m_nGravityMode); } else { m_smSurScan.unregisterListener(m_actHome, m_smSurScan.getDefaultSensor(Sensor.TYPE_GRAVITY)); } if (m_blnGyroEnabled) { m_smSurScan.registerListener(m_actHome, m_smSurScan.getDefaultSensor(Sensor.TYPE_GYROSCOPE), m_nGyroMode); } else { m_smSurScan.unregisterListener(m_actHome, m_smSurScan.getDefaultSensor(Sensor.TYPE_GYROSCOPE)); } if (m_blnMagnetEnabled) { m_smSurScan.registerListener(m_actHome, m_smSurScan.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), m_nMagnetMode); } else { m_smSurScan.unregisterListener(m_actHome, m_smSurScan.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD)); } // Changed on 20150910 // if (m_blnOrientEnabled) { // if (!m_blnAcclEnabled) { // m_smSurScan.registerListener(m_actHome, m_smSurScan.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), m_nOrientMode); // } // // if (!m_blnMagnetEnabled) { // m_smSurScan.registerListener(m_actHome, m_smSurScan.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD), m_nOrientMode); // } // } else { // if (!m_blnAcclEnabled) { // m_smSurScan.unregisterListener(m_actHome, m_smSurScan.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)); // } // // if (!m_blnMagnetEnabled) { // m_smSurScan.unregisterListener(m_actHome, m_smSurScan.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD)); // } // } if (m_blnOrientEnabled) { m_smSurScan.registerListener(m_actHome, m_smSurScan.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR), m_nOrientMode); } else { m_smSurScan.unregisterListener(m_actHome, m_smSurScan.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR)); } if (m_blnLightEnabled) { m_smSurScan.registerListener(m_actHome, m_smSurScan.getDefaultSensor(Sensor.TYPE_LIGHT), m_nLightMode); } else { m_smSurScan.unregisterListener(m_actHome, m_smSurScan.getDefaultSensor(Sensor.TYPE_LIGHT)); } if (m_blnBarometerEnabled) { m_smSurScan.registerListener(m_actHome, m_smSurScan.getDefaultSensor(Sensor.TYPE_PRESSURE), m_nBarometerMode); } else { m_smSurScan.unregisterListener(m_actHome, m_smSurScan.getDefaultSensor(Sensor.TYPE_PRESSURE)); } }
From source file:com.example.sensingapp.SensingApp.java
private void checkSensorAvailability() { //List<Sensor> lstSensor = m_smSurScan.getSensorList(Sensor.TYPE_ORIENTATION); List<Sensor> lstSensor = m_smSurScan.getSensorList(Sensor.TYPE_ROTATION_VECTOR); //Changed on 20150910 if (lstSensor.size() > 0) { m_blnOrientPresent = true;//from w ww. j ava 2 s. c om } else { m_blnOrientPresent = false; m_blnOrientEnabled = false; } lstSensor = m_smSurScan.getSensorList(Sensor.TYPE_GYROSCOPE); if (lstSensor.size() > 0) { m_blnGyroPresent = true; } else { m_blnGyroPresent = false; m_blnGyroEnabled = false; } lstSensor = m_smSurScan.getSensorList(Sensor.TYPE_ACCELEROMETER); if (lstSensor.size() > 0) { m_blnAcclPresent = true; } else { m_blnAcclPresent = false; m_blnAcclEnabled = false; } lstSensor = m_smSurScan.getSensorList(Sensor.TYPE_LINEAR_ACCELERATION); if (lstSensor.size() > 0) { m_blnLinearAcclPresent = true; } else { m_blnLinearAcclPresent = false; m_blnLinearAcclEnabled = false; } lstSensor = m_smSurScan.getSensorList(Sensor.TYPE_GRAVITY); if (lstSensor.size() > 0) { m_blnGravityPresent = true; } else { m_blnGravityPresent = false; m_blnGravityEnabled = false; } lstSensor = m_smSurScan.getSensorList(Sensor.TYPE_MAGNETIC_FIELD); if (lstSensor.size() > 0) { m_blnMagnetPresent = true; } else { m_blnMagnetPresent = false; m_blnMagnetEnabled = false; } lstSensor = m_smSurScan.getSensorList(Sensor.TYPE_LIGHT); if (lstSensor.size() > 0) { m_blnLightPresent = true; } else { m_blnLightPresent = false; m_blnLightEnabled = false; } lstSensor = m_smSurScan.getSensorList(Sensor.TYPE_PRESSURE); if (lstSensor.size() > 0) { m_blnBarometerPresent = true; } else { m_blnBarometerPresent = false; m_blnBarometerEnabled = false; } }
From source file:com.aware.Aware_Preferences.java
/** * Light module settings UI/*from w ww . j av a2s. c om*/ */ private void light() { final PreferenceScreen light_pref = (PreferenceScreen) findPreference("light"); Sensor temp = mSensorMgr.getDefaultSensor(Sensor.TYPE_LIGHT); if (temp != null) { light_pref.setSummary( light_pref.getSummary().toString().replace("*", " - Power: " + temp.getPower() + " mA")); } else { light_pref.setSummary(light_pref.getSummary().toString().replace("*", "")); } final CheckBoxPreference light = (CheckBoxPreference) findPreference(Aware_Preferences.STATUS_LIGHT); light.setChecked(Aware.getSetting(getApplicationContext(), Aware_Preferences.STATUS_LIGHT).equals("true")); light.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { if (mSensorMgr.getDefaultSensor(Sensor.TYPE_LIGHT) == null) { showDialog(DIALOG_ERROR_MISSING_SENSOR); light.setChecked(false); Aware.setSetting(getApplicationContext(), Aware_Preferences.STATUS_LIGHT, false); return false; } Aware.setSetting(getApplicationContext(), Aware_Preferences.STATUS_LIGHT, light.isChecked()); if (light.isChecked()) { framework.startLight(); } else { framework.stopLight(); } return true; } }); final EditTextPreference frequency_light = (EditTextPreference) findPreference( Aware_Preferences.FREQUENCY_LIGHT); if (Aware.getSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_LIGHT).length() > 0) { frequency_light.setSummary( Aware.getSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_LIGHT) + " microseconds"); } frequency_light.setText(Aware.getSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_LIGHT)); frequency_light.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { Aware.setSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_LIGHT, (String) newValue); frequency_light.setSummary((String) newValue + " microseconds"); framework.startLight(); return true; } }); }
From source file:com.zoffcc.applications.zanavi.Navit.java
/** Called when the activity is first created. */ // ----------- remove later ------------- // ----------- remove later ------------- @SuppressLint("NewApi") // ----------- remove later ------------- // ----------- remove later ------------- @TargetApi(Build.VERSION_CODES.FROYO)/*from w w w . j a va 2 s . c om*/ @Override public void onCreate(Bundle savedInstanceState) { // if (Navit.METHOD_DEBUG) Navit.my_func_name(0); // ------- only after API level 9 ------- // ------- only after API level 9 ------- // try // { // StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyDeath().penaltyLog().build()); // StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build()); // // StrictMode.ThreadPolicy old = StrictMode.getThreadPolicy(); // StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder(old).permitDiskWrites().build()); // old = StrictMode.getThreadPolicy(); // StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder(old).permitDiskReads().build()); // // } // catch (NoClassDefFoundError e) // { // } // ------- only after API level 9 ------- // ------- only after API level 9 ------- // Log.e("Navit", "OnCreate"); // if (checkPlayServices()) // { // } ZANaviMainApplication.restore_error_msg(this.getApplicationContext()); // app_status_lastalive = PreferenceManager.getDefaultSharedPreferences(this).getLong(PREF_KEY_LASTALIVE, -1L); app_status_string = PreferenceManager.getDefaultSharedPreferences(this).getString(PREF_KEY_CRASH, "down"); if (FDBL) { p.PREF_enable_debug_crashdetect = PreferenceManager.getDefaultSharedPreferences(this) .getBoolean("enable_debug_crashdetect", true); } else { p.PREF_enable_debug_crashdetect = PreferenceManager.getDefaultSharedPreferences(this) .getBoolean("enable_debug_crashdetect", PLAYSTORE_VERSION_CRASHDETECT); } System.out.println("app_status_string get:[onCreate]" + app_status_string); System.out.println("app_status_string=" + app_status_string); // System.out.println("app_status_string:app_status_lastalive=" + app_status_lastalive); if (app_status_string.compareToIgnoreCase("down") != 0) { if (Navit.CI_ALLOWCRASHREPORTS) { intro_flag_crash = true; System.out.println("app_status_string:1:" + "intro_flag_crash=" + intro_flag_crash); } else { intro_flag_crash = false; } } else { intro_flag_crash = false; } // if (System.currentTimeMillis() > app_status_lastalive + allowed_seconds_alive_for_crash) // { // // reset crash flag after X seconds // intro_flag_crash = false; // } if (checkForUpdate()) { // reset crash flag if we just updated intro_flag_crash = false; } if (!p.PREF_enable_debug_crashdetect) { // reset crash flag if we preference set to "false" intro_flag_crash = false; } // --- if we have no stacktrace -> don't show crash screen ---------- if (intro_flag_crash) { try { if (ZANaviMainApplication.last_stack_trace_as_string == null) { intro_flag_crash = false; } else if (ZANaviMainApplication.last_stack_trace_as_string.length() < 2) { intro_flag_crash = false; } } catch (Exception e) { e.printStackTrace(); } } // --- if we have no stacktrace -> don't show crash screen ---------- System.out.println("app_status_string:2:" + "intro_flag_crash=" + intro_flag_crash); try { app_status_string = "running"; PreferenceManager.getDefaultSharedPreferences(this).edit().putString(PREF_KEY_CRASH, "running") .commit(); System.out.println("app_status_string set:[onCreate]" + app_status_string); } catch (Exception e) { e.printStackTrace(); } api_version_int = Integer.valueOf(android.os.Build.VERSION.SDK); System.out.println("XXX:API=" + api_version_int); if (api_version_int > 10) { Navit.PAINT_OLD_API = false; } else { Navit.PAINT_OLD_API = true; } getPrefs_theme(); getPrefs_theme_main(); Navit.applySharedTheme(this, p.PREF_current_theme_M); super.onCreate(savedInstanceState); Global_Navit_Object = this; asset_mgr = getAssets(); PackageInfo pInfo; try { pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); ZANAVI_VERSION = pInfo.versionName; } catch (NameNotFoundException e4) { } // Intent intent = new Intent(this, ZANaviAboutPage.class); // startActivity(intent); // --------- check permissions ----------- // --------- check permissions ----------- // --------- check permissions ----------- /* * * <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> * <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> * <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" /> * <uses-permission android:name="android.permission.WAKE_LOCK" /> * <uses-permission android:name="android.permission.INTERNET" /> * <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> * <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> */ //if (EasyPermissions.hasPermissions(this, perms)) //{ // // have permissions! //} //else //{ // // ask for permissions // EasyPermissions.requestPermissions(this, Navit.get_text("ZANavi needs some permissions..."), RC_PERM_001, perms); //} // --------- check permissions ----------- // --------- check permissions ----------- // --------- check permissions ----------- OSD_blueish_bg_color = getResources().getColor(R.color.blueish_bg_color); // getBaseContext_ = getBaseContext().getApplicationContext(); getBaseContext_ = getBaseContext(); last_orientation = getResources().getConfiguration().orientation; content_resolver = getContentResolver(); // get_reglevel(); Display display_ = getWindowManager().getDefaultDisplay(); metrics = new DisplayMetrics(); display_.getMetrics(Navit.metrics); road_book_items = new ArrayList<ListViewItem>(); fragmentManager = getSupportFragmentManager(); setContentView(R.layout.main_layout); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); if (toolbar != null) { try { setSupportActionBar(toolbar); // System.out.println("TTT01:" + toolbar); } catch (NoClassDefFoundError e) { } } try { getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE); getSupportActionBar().setDisplayUseLogoEnabled(false); getSupportActionBar().setIcon(R.drawable.icon); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setDisplayShowTitleEnabled(false); } catch (NoClassDefFoundError e) { } catch (Exception e) { e.printStackTrace(); } progressbar_main_activity = (ProgressBar) findViewById(R.id.progressbar_main_activity); progressbar_main_activity.setVisibility(View.GONE); progressbar_main_activity.setProgress(0); // ------------ bottom bar slider ---------------- // ------------ bottom bar slider ---------------- // ------------ bottom bar slider ---------------- if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { smaller_top_bar(true); } else { smaller_top_bar(false); } bottom_bar_px = (int) getResources().getDimension(R.dimen.gui_top_container_height); // System.out.println("VVV:bottom_bar_height:" + bottom_bar_px); bottom_bar_slider_shadow_px = (int) getResources() .getDimension(R.dimen.bottom_slide_view_shadow_compat_height); // System.out.println("VVV:bottom_bar_slider_shadow_px:" + bottom_bar_slider_shadow_px); // final RelativeLayout a = (RelativeLayout) findViewById(R.id.bottom_bar_container); final FrameLayout a = (FrameLayout) findViewById(R.id.bottom_bar_slide); final RelativeLayout.LayoutParams pp22 = (RelativeLayout.LayoutParams) a.getLayoutParams(); // Calculate ToolBar height try { TypedValue tv = new TypedValue(); if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) { actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics()); System.out.println("VVV:abh:" + actionBarHeight); } else { actionBarHeight = NavitGraphics.dp_to_px(144); } } catch (Exception e) { actionBarHeight = NavitGraphics.dp_to_px(144); } final android.support.v7.widget.Toolbar view_toolbar_top = (android.support.v7.widget.Toolbar) findViewById( R.id.toolbar); ViewTreeObserver vto = view_toolbar_top.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { @Override public void onGlobalLayout() { view_toolbar_top.getViewTreeObserver().removeGlobalOnLayoutListener(this); // int width = view_toolbar_top.getMeasuredWidth(); int height = view_toolbar_top.getMeasuredHeight(); Navit.actionBarHeight = height; // System.out.println("hhh:88=" + Navit.actionBarHeight); Navit.cur_y_margin_bottom_bar_touch = Navit.map_view_height + Navit.actionBarHeight + bottom_bar_px - Navit.bottom_bar_slider_shadow_px; // try to put view at bottom pp22.setMargins(0, (int) Navit.cur_y_margin_bottom_bar_touch, 0, 0); // left, top, right, bottom a.setLayoutParams(pp22); a.requestLayout(); } }); // actionBarHeight = 168; // final int SWIPE_MIN_DISTANCE = NavitGraphics.dp_to_px(25); // final float SWIPE_THRESHOLD_VELOCITY = 5.5f; // final float FLING_PIXELS_PER_SECOND = 100; // final float maxFlingVelocity = ViewConfiguration.get(this).getScaledMaximumFlingVelocity(); final ViewConfiguration vc = ViewConfiguration.get(this); final int swipeMinDistance = vc.getScaledPagingTouchSlop(); final int swipeThresholdVelocity = vc.getScaledMinimumFlingVelocity(); swipeMaxOffPath = vc.getScaledTouchSlop(); // (there is also vc.getScaledMaximumFlingVelocity() one could check against) // setup some values -------- NavitGraphics.long_press_on_screen_max_distance = swipeMaxOffPath; // setup some values -------- class MyGestureDetector extends SimpleOnGestureListener { @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { try { // float velocityPercentY = velocityY / maxFlingVelocity; // the percent is a value in the range of (0, 1] // float normalizedVelocityY = velocityPercentY * FLING_PIXELS_PER_SECOND; // where PIXELS_PER_SECOND is a device-independent measurement // System.out.println("VVV:" + (e1.getY() - e2.getY()) + " " + NavitGraphics.dp_to_px((int) (e1.getY() - e2.getY())) + " " + maxFlingVelocity + " " + velocityY + " " + velocityPercentY + " " + normalizedVelocityY + " " + SWIPE_THRESHOLD_VELOCITY); // System.out.println("VVV:2:" + swipeMinDistance + " " + swipeThresholdVelocity + " " + swipeMaxOffPath); // bottom to top if (e1.getY() - e2.getY() > swipeMinDistance && Math.abs(velocityY) > swipeThresholdVelocity) { //int featureWidth = getMeasuredWidth(); //mActiveFeature = (mActiveFeature < (mItems.size() - 1)) ? mActiveFeature + 1 : mItems.size() - 1; //smoothScrollTo(mActiveFeature * featureWidth, 0); //System.out.println("GS:002:up:" + velocityY + " " + e2.getY() + " " + e1.getY()); animate_bottom_bar_up(); return true; } // top to bottom else if (e2.getY() - e1.getY() > swipeMinDistance && Math.abs(velocityY) > swipeThresholdVelocity) { //int featureWidth = getMeasuredWidth(); //mActiveFeature = (mActiveFeature > 0) ? mActiveFeature - 1 : 0; //smoothScrollTo(mActiveFeature * featureWidth, 0); //System.out.println("GS:003:down:" + velocityY + " " + e1.getY() + " " + e2.getY()); animate_bottom_bar_down(); return true; } } catch (Exception e) { //System.out.println("GS:009:EE:" + e.getMessage()); } return false; } } mGestureDetector = new GestureDetector(new MyGestureDetector()); push_pin_view = (ImageView) findViewById(R.id.bottom_slide_left_side); push_pin_view.setOnClickListener(new ImageView.OnClickListener() { public void onClick(View v) { try { toggle_follow_button(); } catch (Exception e) { } } }); cur_y_margin_bottom_bar_touch = 0; // try to put view at bottom a.setOnTouchListener(new View.OnTouchListener() { @Override synchronized public boolean onTouch(View v, MotionEvent m) { int action = m.getAction(); if (mGestureDetector.onTouchEvent(m)) { //System.out.println("GS:001:fling!!"); // System.out.println("FRAG:fling:011"); return true; } else if (action == MotionEvent.ACTION_DOWN) { last_y_bottom_bar_touch = m.getY(); // put roadbook into layout ----------- FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); try { if (road_book == null) { road_book = new ZANaviRoadbookFragment(); // System.out.println("FRAG:attach:001"); fragmentTransaction.replace(R.id.roadbook_fragment_container, road_book, ""); fragmentTransaction.commitAllowingStateLoss(); // fragmentTransaction.show(road_book); } else { // System.out.println("FRAG:attached:003"); } } catch (Exception ef) { } // put roadbook into layout ----------- return true; } else if ((action == MotionEvent.ACTION_UP) || (action == MotionEvent.ACTION_CANCEL)) { // System.out.println("FRAG:up/cancel:012"); // release if (cur_y_margin_bottom_bar_touch > (bottom_y_margin_bottom_bar_touch / 2)) { // snap back to bottom animate_bottom_bar_down(); } else { // snap top top animate_bottom_bar_up(); } } else // if (action == MotionEvent.ACTION_MOVE) { // System.out.println("FRAG:*else*:012"); if (Math.abs(last_y_bottom_bar_touch - m.getY()) > 2) { float last_margin = cur_y_margin_bottom_bar_touch; cur_y_margin_bottom_bar_touch = cur_y_margin_bottom_bar_touch - (last_y_bottom_bar_touch - m.getY()); if ((cur_y_margin_bottom_bar_touch >= 0) && (cur_y_margin_bottom_bar_touch <= bottom_y_margin_bottom_bar_touch)) { // System.out.println("VVV:move:" + cur_y_margin_bottom_bar_touch + " " + bottom_y_margin_bottom_bar_touch); last_y_bottom_bar_touch = m.getY() + (last_y_bottom_bar_touch - m.getY()); RelativeLayout.LayoutParams relativeParams = (RelativeLayout.LayoutParams) a .getLayoutParams(); relativeParams.setMargins(0, (int) cur_y_margin_bottom_bar_touch, 0, 0); // left, top, right, bottom a.setLayoutParams(relativeParams); a.requestLayout(); } else { // System.out.println("VVV:revert"); // revert position cur_y_margin_bottom_bar_touch = last_margin; } } } return true; } }); // ------------ bottom bar slider ---------------- // ------------ bottom bar slider ---------------- // ------------ bottom bar slider ---------------- // init cancel dialog!! ---------- // init cancel dialog!! ---------- Message msg2 = new Message(); Bundle b2 = new Bundle(); b2.putString("text", ""); msg2.what = 0; msg2.setData(b2); ZANaviDownloadMapCancelActivity.canceldialog_handler.sendMessage(msg2); // init cancel dialog!! ---------- // init cancel dialog!! ---------- app_window = getWindow(); // ---------------- set some directories ----------------- // ---------------- set some directories ----------------- NAVIT_DATA_DIR = this.getFilesDir().getPath(); this.getFilesDir().mkdirs(); // --- // System.out.println("data dir=" + NAVIT_DATA_DIR); NAVIT_DATA_SHARE_DIR = NAVIT_DATA_DIR + "/share/"; File tmp3 = new File(NAVIT_DATA_SHARE_DIR); tmp3.mkdirs(); // --- FIRST_STARTUP_FILE = NAVIT_DATA_SHARE_DIR + "/has_run_once.txt"; VERSION_FILE = NAVIT_DATA_SHARE_DIR + "/version.txt"; // ---------------- set some directories ----------------- // ---------------- set some directories ----------------- try { toneG = new ToneGenerator(AudioManager.STREAM_MUSIC, 100); } catch (Exception e) { } try { Class.forName("android.app.backup.BackupManager"); backupManager = new BackupManager(this); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } int width_ = display_.getWidth(); int height_ = display_.getHeight(); Log.e("Navit", "Navit -> pixels x=" + width_ + " pixels y=" + height_); Log.e("Navit", "Navit -> dpi=" + Navit.metrics.densityDpi); Log.e("Navit", "Navit -> density=" + Navit.metrics.density); Log.e("Navit", "Navit -> scaledDensity=" + Navit.metrics.scaledDensity); try { // send overspill factor to C-code Message msg33 = new Message(); Bundle b33 = new Bundle(); b33.putInt("Callback", 104); msg33.setData(b33); NavitGraphics.callback_handler.sendMessage(msg33); } catch (Exception eee) { } // ----- service ----- // ----- service ----- ZANaviMapDownloaderServiceIntent = new Intent(Navit.getBaseContext_, ZANaviMapDownloaderService.class); // ----- service ----- // ----- service ----- System.out.println("Navit:onCreate:JTHREAD ID=" + Thread.currentThread().getId()); System.out.println("Navit:onCreate:THREAD ID=" + NavitGraphics.GetThreadId()); // bitmaps for lanes lane_left = BitmapFactory.decodeResource(getResources(), R.drawable.lane_left); lane_right = BitmapFactory.decodeResource(getResources(), R.drawable.lane_right); lane_merge_to_left = BitmapFactory.decodeResource(getResources(), R.drawable.lane_merge_to_left); lane_merge_to_right = BitmapFactory.decodeResource(getResources(), R.drawable.lane_merge_to_right); lane_none = BitmapFactory.decodeResource(getResources(), R.drawable.lane_none); // bitmaps for lanes // paint for bitmapdrawing on map NavitGraphics.paint_for_map_display.setAntiAlias(true); NavitGraphics.paint_for_map_display.setFilterBitmap(true); // sky NavitGraphics.paint_sky_day.setAntiAlias(true); NavitGraphics.paint_sky_day.setColor(Color.parseColor("#79BAEC")); NavitGraphics.paint_sky_night.setAntiAlias(true); NavitGraphics.paint_sky_night.setColor(Color.parseColor("#090909")); // stars NavitGraphics.paint_sky_night_stars.setColor(Color.parseColor("#DEDDEF")); // twilight NavitGraphics.paint_sky_twilight1.setColor(Color.parseColor("#090909")); NavitGraphics.paint_sky_twilight2.setColor(Color.parseColor("#113268")); NavitGraphics.paint_sky_twilight3.setColor(Color.parseColor("#79BAEC")); Random m = new Random(); int i6 = 0; for (i6 = 0; i6 < (NavitGraphics.max_stars + 1); i6++) { NavitGraphics.stars_x[i6] = m.nextFloat(); NavitGraphics.stars_y[i6] = m.nextFloat(); NavitGraphics.stars_size[i6] = m.nextInt(3) + 1; } res_ = getResources(); int ii = 0; NavitGraphics.dl_thread_cur = 0; for (ii = 0; ii < NavitGraphics.dl_thread_max; ii++) { NavitGraphics.dl_thread[ii] = null; } String font_file_name = "Roboto-Regular.ttf"; // "LiberationSans-Regular.ttf"; NavitStreetnameFont = Typeface.createFromAsset(getBaseContext().getAssets(), font_file_name); // System.out.println("NavitStreetnameFont" + NavitStreetnameFont); Navit_maps_loaded = false; // only take arguments here, onResume gets called all the time (e.g. when screenblanks, etc.) Navit.startup_intent = this.getIntent(); // hack! remeber timstamp, and only allow 4 secs. later in onResume to set target! Navit.startup_intent_timestamp = System.currentTimeMillis(); Log.e("Navit", "**1**A " + startup_intent.getAction()); Log.e("Navit", "**1**D " + startup_intent.getDataString()); Log.e("Navit", "**1**I " + startup_intent.toString()); try { Log.e("Navit", "**1**DH E " + startup_intent.getExtras().describeContents()); } catch (Exception ee) { } startup_status = Navit_Status_NORMAL_STARTUP; // glSurfaceView = (GLSurfaceView) findViewById(R.id.glSurfaceView_001); // glSurfaceView.setEGLContextClientVersion(2); // enable OpenGL 2.0 // glSurfaceView.setRenderer(new GlRenderer()); // glSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); // only render on demand // // // draw some sample lines ---- // // draw some sample lines ---- // // draw some sample lines ---- // ZANaviGlLine vertLine = new ZANaviGlLine(); // vertLine.SetVerts(1000f, 1000f, 0f, -1000f, -1000f, 0f); // vertLine.SetColor(.8f, .8f, 0f, 1.0f); // // float[] mMVPMatrix = new float[16]; // // // Position the eye behind the origin. // final float eyeX = 0.0f; // final float eyeY = 0.0f; // final float eyeZ = 1.5f; // // // We are looking toward the distance // final float lookX = 0.0f; // final float lookY = 0.0f; // final float lookZ = -5.0f; // // // Set our up vector. This is where our head would be pointing were we holding the camera. // final float upX = 0.0f; // final float upY = 1.0f; // final float upZ = 0.0f; // // // Set the view matrix. This matrix can be said to represent the camera position. // // NOTE: In OpenGL 1, a ModelView matrix is used, which is a combination of a model and // // view matrix. In OpenGL 2, we can keep track of these matrices separately if we choose. // Matrix.setLookAtM(mMVPMatrix, 0, eyeX, eyeY, eyeZ, lookX, lookY, lookZ, upX, upY, upZ); // // vertLine.draw(mMVPMatrix); // // glSurfaceView.postInvalidate(); // glSurfaceView.requestRender(); // glSurfaceView.postInvalidate(); // // draw some sample lines ---- // // draw some sample lines ---- // // draw some sample lines ---- // setup graphics objects // setup graphics objects // setup graphics objects NG__vehicle = new NavitGraphics(this, 1, 0, 0, 50, 50, 65535, 0, 0); NG__map_main = new NavitGraphics(this, 0, 0, 0, 100, 100, 0, 0, 0); Navit.N_NavitGraphics = NG__map_main; // setup graphics objects // setup graphics objects // setup graphics objects NV = new NavitVehicle(this); NSp = new NavitSpeech2(this); // init translated text ------------------------------------ // NavitTextTranslations.init(); final Runnable r = new Runnable() { public void run() { NavitTextTranslations.init(); } }; ThreadGroup group = new ThreadGroup("Group1"); new Thread(group, r, "ZTransInit1", 100000).start(); // use 0.1MByte stack // init translated text ------------------------------------ // set the new locale here ----------------------------------- getPrefs_loc(); activatePrefs_loc(); // set the new locale here ----------------------------------- // get the local language ------------- Locale locale = java.util.Locale.getDefault(); String lang = locale.getLanguage(); String langu = lang; String langc = lang; Log.e("Navit", "lang=" + lang); int pos = langu.indexOf('_'); if (pos != -1) { langc = langu.substring(0, pos); langu = langc + langu.substring(pos).toUpperCase(locale); Log.e("Navit", "substring lang " + langu.substring(pos).toUpperCase(locale)); // set lang. for translation NavitTextTranslations.main_language = langc; NavitTextTranslations.sub_language = langu.substring(pos).toUpperCase(locale); } else { String country = locale.getCountry(); Log.e("Navit", "Country1 " + country); Log.e("Navit", "Country2 " + country.toUpperCase(locale)); langu = langc + "_" + country.toUpperCase(locale); // set lang. for translation NavitTextTranslations.main_language = langc; NavitTextTranslations.sub_language = country.toUpperCase(locale); } Log.e("Navit", "Language " + lang); // get the local language ------------- TextView no_maps_text = (TextView) this.findViewById(R.id.no_maps_text); no_maps_text.setText("\n\n\n" + Navit.get_text("No Maps installed") + "\n" + Navit.get_text("Please download a map") + "\n\n"); // if (api_version_int < 11) // { try { try { no_maps_text.setVisibility(View.INVISIBLE); } catch (NoSuchMethodError e) { } try { no_maps_text.setActivated(false); } catch (NoSuchMethodError e) { } } catch (Exception e) { e.printStackTrace(); } // } // no_maps_text.postInvalidate(); // set map cache size here ----------------------------------- getPrefs_mapcache(); activatePrefs_mapcache(); // set map cache size here ----------------------------------- // get map data dir and set it ----------------------------- getPrefs_mapdir(); activatePrefs_mapdir(true); // get map data dir and set it ----------------------------- // get special prefs here ------------------------------------ get_prefs_highdpi(); // get special prefs here ------------------------------------ // make sure the new path for the navitmap.bin file(s) exist!! File navit_maps_dir = new File(MAP_FILENAME_PATH); navit_maps_dir.mkdirs(); // create nomedia files File nomedia_file = new File(MAP_FILENAME_PATH + ".nomedia"); try { nomedia_file.createNewFile(); } catch (Exception e1) { e1.printStackTrace(); } // create nomedia files // check if we already have a borders.bin file (if not, then extract the included simplified one) File b_ = new File(MAP_FILENAME_PATH + "/borders.bin"); try { if (!b_.exists()) { try { File c_ = new File(MAPMD5_FILENAME_PATH + "/borders.bin.md5"); c_.delete(); } catch (Exception e2) { } Log.e("Navit", "trying to extract borders simple resource to:" + MAP_FILENAME_PATH + "/borders.bin"); if (!extractRes("borders_simple", MAP_FILENAME_PATH + "/borders.bin")) { Log.e("Navit", "Failed to extract borders simple resource to:" + MAP_FILENAME_PATH + "/borders.bin"); } } } catch (Exception e) { } // check if we already have a borders.bin file // make sure the new path for config files exist File navit_cfg_dir = new File(CFG_FILENAME_PATH); navit_cfg_dir.mkdirs(); // make sure the new path for the navitmap.bin file(s) exist!! File navit_mapsmd5_dir = new File(MAPMD5_FILENAME_PATH); navit_mapsmd5_dir.mkdirs(); // make sure the share dir exists, otherwise the infobox will not show File navit_data_share_dir = new File(NAVIT_DATA_SHARE_DIR); navit_data_share_dir.mkdirs(); File dd = new File(NAVIT_DATA_DEBUG_DIR); dd.mkdirs(); // try to create cat. file if it does not exist File navit_maps_catalogue = new File(CFG_FILENAME_PATH + NavitMapDownloader.CAT_FILE); if (!navit_maps_catalogue.exists()) { FileOutputStream fos_temp; try { fos_temp = new FileOutputStream(navit_maps_catalogue); fos_temp.write((NavitMapDownloader.MAP_CAT_HEADER + "\n").getBytes()); // just write header to the file fos_temp.flush(); fos_temp.close(); } catch (Exception e) { e.printStackTrace(); } } // ---------- downloader threads ---------------- PackageInfo pkgInfo; Navit_DonateVersion_Installed = false; try { // is the donate version installed? pkgInfo = getPackageManager().getPackageInfo("com.zoffcc.applications.zanavi_donate", 0); String sharedUserId = pkgInfo.sharedUserId; System.out.println("str nd=" + sharedUserId); if (sharedUserId.equals("com.zoffcc.applications.zanavi")) { System.out.println("##bonus 001##"); Navit_DonateVersion_Installed = true; NavitMapDownloader.MULTI_NUM_THREADS = NavitMapDownloader.MULTI_NUM_THREADS_MAX; } } catch (NameNotFoundException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } try { if (get_reglevel() == 1) { System.out.println("##U:bonus 001##"); Navit_DonateVersion_Installed = true; NavitMapDownloader.MULTI_NUM_THREADS = NavitMapDownloader.MULTI_NUM_THREADS_MAX; } } catch (Exception e) { e.printStackTrace(); } try { // is the "large map" donate version installed? pkgInfo = getPackageManager().getPackageInfo("com.zoffcc.applications.zanavi_largemap_donate", 0); String sharedUserId = pkgInfo.sharedUserId; System.out.println("str lm=" + sharedUserId); if (sharedUserId.equals("com.zoffcc.applications.zanavi")) { System.out.println("##bonus 002##"); Navit_DonateVersion_Installed = true; Navit_Largemap_DonateVersion_Installed = true; NavitMapDownloader.MULTI_NUM_THREADS = NavitMapDownloader.MULTI_NUM_THREADS_MAX; } } catch (NameNotFoundException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } try { if (get_reglevel() == 1) { System.out.println("##U:bonus 002##"); Navit_DonateVersion_Installed = true; Navit_Largemap_DonateVersion_Installed = true; NavitMapDownloader.MULTI_NUM_THREADS = NavitMapDownloader.MULTI_NUM_THREADS_MAX; } } catch (Exception e) { e.printStackTrace(); } // update map list NavitMapDownloader.init_maps_without_donate_largemaps(); // ---------- downloader threads ---------------- // ---- detect menu button ---- detect_menu_button(); if (Navit.metrics.densityDpi >= 320) //&& (PREF_shrink_on_high_dpi)) { Navit.menu_button = BitmapFactory.decodeResource(getResources(), R.drawable.menu_001); } else { Navit.menu_button = BitmapFactory.decodeResource(getResources(), R.drawable.menu_001_small); } Navit.long_green_arrow = BitmapFactory.decodeResource(getResources(), R.drawable.long_green_arrow); Navit.follow_on = BitmapFactory.decodeResource(getResources(), R.drawable.follow); Navit.follow_off = BitmapFactory.decodeResource(getResources(), R.drawable.follow_off); Navit.follow_current = Navit.follow_on; if ((Navit.metrics.densityDpi >= 320) && (p.PREF_shrink_on_high_dpi)) { float factor; factor = (float) NavitGraphics.Global_Scaled_DPI_normal / (float) Navit.metrics.densityDpi; factor = factor * 1.7f; // BitmapFactory.Options o = new BitmapFactory.Options(); o.inDither = true; //o.inScaled = true; //o.inTargetDensity = NavitGraphics.Global_Scaled_DPI_normal; Navit.nav_arrow_stopped = BitmapFactory.decodeResource(getResources(), R.drawable.navigation_arrow_stopped, o); Navit.nav_arrow_moving = BitmapFactory.decodeResource(getResources(), R.drawable.navigation_arrow_moving, o); Navit.nav_arrow_moving_grey = BitmapFactory.decodeResource(getResources(), R.drawable.navigation_arrow_moving_grey, o); Navit.nav_arrow_moving_shadow = BitmapFactory.decodeResource(getResources(), R.drawable.navigation_arrow_moving_shadow, o); Navit.nav_arrow_stopped_small = Bitmap.createScaledBitmap(Navit.nav_arrow_stopped, (int) (Navit.nav_arrow_stopped.getWidth() / NavitGraphics.strech_factor_3d_map * factor), (int) (Navit.nav_arrow_stopped.getHeight() / NavitGraphics.strech_factor_3d_map * factor), true); Navit.nav_arrow_moving_small = Bitmap.createScaledBitmap(Navit.nav_arrow_moving, (int) (Navit.nav_arrow_moving.getWidth() / NavitGraphics.strech_factor_3d_map * factor), (int) (Navit.nav_arrow_moving.getHeight() / NavitGraphics.strech_factor_3d_map * factor), true); Navit.nav_arrow_moving_shadow_small = Bitmap.createScaledBitmap(Navit.nav_arrow_moving_shadow, (int) (Navit.nav_arrow_moving_shadow.getWidth() / NavitGraphics.strech_factor_3d_map * factor), (int) (Navit.nav_arrow_moving_shadow.getHeight() / NavitGraphics.strech_factor_3d_map * factor), true); } else { Navit.nav_arrow_stopped = BitmapFactory.decodeResource(getResources(), R.drawable.navigation_arrow_stopped); Navit.nav_arrow_moving = BitmapFactory.decodeResource(getResources(), R.drawable.navigation_arrow_moving); Navit.nav_arrow_moving_grey = BitmapFactory.decodeResource(getResources(), R.drawable.navigation_arrow_moving_grey); Navit.nav_arrow_moving_shadow = BitmapFactory.decodeResource(getResources(), R.drawable.navigation_arrow_moving_shadow); Navit.nav_arrow_stopped_small = Bitmap.createScaledBitmap(Navit.nav_arrow_stopped, (int) (Navit.nav_arrow_stopped.getWidth() / NavitGraphics.strech_factor_3d_map), (int) (Navit.nav_arrow_stopped.getHeight() / NavitGraphics.strech_factor_3d_map), true); Navit.nav_arrow_moving_small = Bitmap.createScaledBitmap(Navit.nav_arrow_moving, (int) (Navit.nav_arrow_moving.getWidth() / NavitGraphics.strech_factor_3d_map), (int) (1.5 * Navit.nav_arrow_moving.getHeight() / NavitGraphics.strech_factor_3d_map), true); Navit.nav_arrow_moving_shadow_small = Bitmap.createScaledBitmap(Navit.nav_arrow_moving_shadow, (int) (Navit.nav_arrow_moving_shadow.getWidth() / NavitGraphics.strech_factor_3d_map), (int) (1.5 * Navit.nav_arrow_moving_shadow.getHeight() / NavitGraphics.strech_factor_3d_map), true); } Navit.zoomin = BitmapFactory.decodeResource(getResources(), R.drawable.zoom_in_32_32); Navit.zoomout = BitmapFactory.decodeResource(getResources(), R.drawable.zoom_out_32_32); //Navit.oneway_arrow = BitmapFactory.decodeResource(getResources(), R.drawable.oneway); Navit.oneway_arrow = BitmapFactory.decodeResource(getResources(), R.drawable.oneway_large); Navit.oneway_bicycle_arrow = BitmapFactory.decodeResource(getResources(), R.drawable.oneway_bicycle_large); // ******************* // ******************* // ******************* // ******************* // check/init the catalogue file for downloaded maps NavitMapDownloader.init_cat_file(); // ******************* // ******************* // ******************* // ******************* xmlconfig_unpack_file = false; write_new_version_file = false; try { NavitAppVersion = "" + this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionCode; NavitAppVersion_string = "" + this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName; } catch (NameNotFoundException e) { e.printStackTrace(); NavitAppVersion = "1"; NavitAppVersion_string = "1"; } catch (Exception e) { e.printStackTrace(); NavitAppVersion = "2"; NavitAppVersion_string = "2"; } try { File navit_version = new File(VERSION_FILE); if (!navit_version.exists()) { System.out.println("version file does not exist"); NavitAppVersion_prev = "-1"; write_new_version_file = true; } else { // files exists, read in the prev. verison number System.out.println("version file is here"); FileInputStream fos_temp; byte[] buffer = new byte[101]; fos_temp = new FileInputStream(navit_version); int len = fos_temp.read(buffer, 0, 100); if (len != -1) { // use only len bytes to make the string (the rest is garbage!!) NavitAppVersion_prev = new String(buffer).substring(0, len); } else { NavitAppVersion_prev = "-1"; write_new_version_file = true; } fos_temp.close(); } } catch (Exception e) { NavitAppVersion_prev = "-1"; write_new_version_file = true; e.printStackTrace(); } System.out.println("vprev:" + NavitAppVersion_prev + " vcur:" + NavitAppVersion); intro_flag_update = false; if (NavitAppVersion_prev.compareTo(NavitAppVersion) != 0) { // different version System.out.println("different version!!"); write_new_version_file = true; xmlconfig_unpack_file = true; //if ((NavitAppVersion_prev.compareTo("-1") != 0) && (NavitAppVersion.compareTo("-1") != 0)) //{ // user has upgraded to a new version of ZANavi startup_status = Navit_Status_UPGRADED_TO_NEW_VERSION; intro_flag_update = true; //} } else { // same version System.out.println("same version"); xmlconfig_unpack_file = false; } // write new version file if (write_new_version_file) { try { System.out.println("write version file"); FileOutputStream fos_temp; File navit_version = new File(VERSION_FILE); navit_version.delete(); fos_temp = new FileOutputStream(navit_version); fos_temp.write(NavitAppVersion.getBytes()); fos_temp.flush(); fos_temp.close(); } catch (Exception e) { e.printStackTrace(); } } // Sample useragent strings: // // Mozilla/5.0 (Windows NT 6.1; WOW64; rv:7.0a1) Gecko/20110616 Firefox/7.0a1 SeaMonkey/2.4a1 // Dalvik/1.4.0 (Linux; U; Android 2.3.3; GT-I9100 Build/GINGERBREAD) // Dalvik/1.2.0 (Linux; U; Android 2.2.1; GT-S5830 Build/FROYO) // Dalvik/1.4.0 (Linux; U; Android 2.3.3; HTC Desire S Build/GRI40) // Dalvik/1.2.0 (Linux; U; Android 2.2.2; MB525 Build/3.4.2-179) // Dalvik/1.4.0 (Linux; U; Android 2.3.3; HTC Wildfire S A510e Build/GRI40) // Wget/1.10.2 // Dalvik/1.4.0 (Linux; U; Android 2.3.3; sdk Build/GRI34) // Dalvik/1.2.0 (Linux; U; Android 2.2.2; MB525 Build/3.4.2-164) // Dalvik/1.2.0 (Linux; U; Android 2.2; GT-I9000 Build/FROYO) // Dalvik/1.2.0 (Linux; U; Android 2.2.1; GT-S5570L Build/FROYO) // Dalvik/1.2.0 (Linux; U; Android 2.2.1; GT-I9000 Build/FROYO) // Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; InfoPath.1) String ANDROID = android.os.Build.VERSION.SDK; //The current development codename, or the string "REL" if this is a release build. //String BOARD = android.os.Build.BOARD; //The name of the underlying board, like "goldfish". //String BOOTLOADER = android.os.Build.BOOTLOADER; // The system bootloader version number. String BRAND = android.os.Build.BRAND; //The brand (e.g., carrier) the software is customized for, if any. //String CPU_ABI = android.os.Build.CPU_ABI; //The name of the instruction set (CPU type + ABI convention) of native code. //String CPU_ABI2 = android.os.Build.CPU_ABI2; // The name of the second instruction set (CPU type + ABI convention) of native code. String DEVICE = android.os.Build.DEVICE; // The name of the industrial design. String DISPLAY = android.os.Build.DISPLAY; //A build ID string meant for displaying to the user //String FINGERPRINT = android.os.Build.FINGERPRINT; //A string that uniquely identifies this build. //String HARDWARE = android.os.Build.HARDWARE; //The name of the hardware (from the kernel command line or /proc). //String HOST = android.os.Build.HOST; //String ID = android.os.Build.ID; //Either a changelist number, or a label like "M4-rc20". String MANUFACTURER = android.os.Build.MANUFACTURER; //The manufacturer of the product/hardware. //String MODEL = android.os.Build.MODEL; //The end-user-visible name for the end product. //String PRODUCT = android.os.Build.PRODUCT; //The name of the overall product. //String RADIO = android.os.Build.RADIO; //The radio firmware version number. //String TAGS = android.os.Build.TAGS; //Comma-separated tags describing the build, like "unsigned,debug". //String TYPE = android.os.Build.TYPE; //The type of build, like "user" or "eng". //String USER = android.os.Build.USER; String android_version = "Android " + ANDROID; String android_device = MANUFACTURER + " " + BRAND + " " + DEVICE; if (MANUFACTURER.equalsIgnoreCase("amazon")) { // we are on amazon device ZANaviNormalDonateActivity.on_amazon_device = true; } // debug // debug // android_device = "telechips telechips m801"; // debug // debug String android_rom_name = DISPLAY; if (FDBL) { android_rom_name = android_rom_name + "; FD"; } if (Navit_DonateVersion_Installed == false) { UserAgentString = "Mozilla/5.0 (Linux; U; " + "Z" + NavitAppVersion + "; " + android_version + "; " + android_device + " " + android_rom_name + ")"; UserAgentString_bind = "Mozilla/5.0 @__THREAD__@ (Linux; U; " + "Z" + NavitAppVersion + "; " + android_version + "; " + android_device + " " + android_rom_name + ")"; } else { if (Navit_Largemap_DonateVersion_Installed == false) { UserAgentString = "Mozilla/5.0 (Linux; U; " + "donateZ" + NavitAppVersion + "; " + android_version + "; " + android_device + " " + android_rom_name + ")"; UserAgentString_bind = "Mozilla/5.0 @__THREAD__@ (Linux; U; " + "donateZ" + NavitAppVersion + "; " + android_version + "; " + android_device + " " + android_rom_name + ")"; } else { UserAgentString = "Mozilla/5.0 (Linux; U; " + "LMdonateLMZ" + NavitAppVersion + "; " + android_version + "; " + android_device + " " + android_rom_name + ")"; UserAgentString_bind = "Mozilla/5.0 @__THREAD__@ (Linux; U; " + "LMdonateLMZ" + NavitAppVersion + "; " + android_version + "; " + android_device + " " + android_rom_name + ")"; } } // System.out.println("UA=" + UserAgentString); // --------- enable GPS ? -------------- // --------- enable GPS ? -------------- // try // { // final LocationManager llmanager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // if (!llmanager.isProviderEnabled(LocationManager.GPS_PROVIDER)) // { // buildAlertMessageNoGps(); // } // } // catch (Exception e) // { // e.printStackTrace(); // } // --------- enable GPS ? -------------- // --------- enable GPS ? -------------- unsupported = false; try { if (android_device.toLowerCase().contains("telechips")) { if (android_device.toLowerCase().contains("m801")) { // if the donate version is already installed, dont disable the app if (Navit_DonateVersion_Installed == false) { if (Navit_Largemap_DonateVersion_Installed == false) { // activate [Weltbild] Cat Nova again (19.12.2011) // ** // unsupported = true; } } } } } catch (Exception e) { e.printStackTrace(); } try { // this hangs the emulator, if emulator < 2.3 (only works in emulator >= 2.3)!! if (!NAVIT_IS_EMULATOR) { sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); } } catch (Exception e3) { e3.printStackTrace(); } // try // { // vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); // } // catch (Exception e) // { // e.printStackTrace(); // } //sensorManager_ = sensorManager; // light sensor ------------------- try { lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); lightsensor_max_value = lightSensor.getMaximumRange(); lightSensorEventListener = new SensorEventListener() { @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } @Override public void onSensorChanged(SensorEvent event) { try { if (p.PREF_auto_night_mode) { if (event.sensor.getType() == Sensor.TYPE_LIGHT) { if (Navit.DEBUG_LUX_VALUE) { debug_cur_lux_value = event.values[0]; NavitGraphics.NavitAOverlay_s.postInvalidate(); } // System.out.println("Current Reading(Lux): cur=" + event.values[0] + " max=" + lightsensor_max_value); if (night_mode == false) { if (event.values[0] < p.PREF_night_mode_lux) { night_mode = true; set_night_mode(1); draw_map(); } } else if (night_mode == true) { if (event.values[0] > (p.PREF_night_mode_lux + p.PREF_night_mode_buffer)) { night_mode = false; set_night_mode(0); draw_map(); } } } } else { try { sensorManager.unregisterListener(lightSensorEventListener); System.out.println("stop lightsensor"); } catch (Exception e) { } try { night_mode = false; set_night_mode(0); draw_map(); } catch (Exception e) { } } } catch (Exception e) { // e.printStackTrace(); } } }; } catch (Exception e) { } // light sensor ------------------- generic_alert_box = new AlertDialog.Builder(this); /* * show info box for first time users */ AlertDialog.Builder infobox = new AlertDialog.Builder(this); //. english text: Welcome to ZANavi infobox.setTitle(Navit.get_text("__INFO_BOX_TITLE__")); //TRANS infobox.setCancelable(false); final TextView message = new TextView(this); message.setFadingEdgeLength(20); message.setVerticalFadingEdgeEnabled(true); message.setPadding(10, 5, 10, 5); message.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18); message.setGravity(Gravity.LEFT); // message.setScrollBarStyle(TextView.SCROLLBARS_INSIDE_OVERLAY); // message.setVerticalScrollBarEnabled(true); RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT); rlp.leftMargin = 7; rlp.rightMargin = 7; Navit.Navit_Geocoder = null; try { // for online search Navit.Navit_Geocoder = new Geocoder(this); } catch (Exception e) { e.printStackTrace(); } // if (api_version_int < 11) // { // //TRANS // infobox.setPositiveButton(Navit.get_text("Ok"), new DialogInterface.OnClickListener() // { // public void onClick(DialogInterface arg0, int arg1) // { // Log.e("Navit", "Ok, user saw the infobox"); // } // }); // // //TRANS // infobox.setNeutralButton(Navit.get_text("More info"), new DialogInterface.OnClickListener() // { // public void onClick(DialogInterface arg0, int arg1) // { // Log.e("Navit", "user wants more info, show the website"); // // URL to ZANavi Manual (in english language) // String url = "http://zanavi.cc/index.php/Manual"; // if (FDBL) // { // url = "http://fd.zanavi.cc/manual"; // } // Intent i = new Intent(Intent.ACTION_VIEW); // i.setData(Uri.parse(url)); // startActivity(i); // } // }); // } info_popup_seen_count_end = false; File navit_first_startup = new File(FIRST_STARTUP_FILE); // if file does NOT exist, show the info box if (!navit_first_startup.exists()) { // set first-ever-startup flag first_ever_startup = true; info_popup_seen_count_end = true; // don't show on first ever start of the app startup_status = Navit_Status_COMPLETE_NEW_INSTALL; FileOutputStream fos_temp; try { info_popup_seen_count++; fos_temp = new FileOutputStream(navit_first_startup); fos_temp.write((int) info_popup_seen_count); // use to store info popup seen count fos_temp.flush(); fos_temp.close(); // if (api_version_int < 11) // { // message.setLayoutParams(rlp); // //. TRANSLATORS: multiline info text for first startup of application (see en_US for english text) // final SpannableString s = new SpannableString(" " + Navit.get_text("__INFO_BOX_TEXT__")); //TRANS // Linkify.addLinks(s, Linkify.WEB_URLS); // message.setText(s); // message.setMovementMethod(LinkMovementMethod.getInstance()); // infobox.setView(message); // infobox.show(); // } } catch (Exception e) { e.printStackTrace(); } } else { FileOutputStream fos_temp; FileInputStream fis_temp; try { fis_temp = new FileInputStream(navit_first_startup); info_popup_seen_count = fis_temp.read(); fis_temp.close(); if (info_popup_seen_count < 0) { info_popup_seen_count = 0; } // we wrote "A" -> (int)65 previously, so account for that if (info_popup_seen_count == 65) { info_popup_seen_count = 0; } if (info_popup_seen_count > info_popup_seen_count_max) { info_popup_seen_count_end = true; } else { info_popup_seen_count++; fos_temp = new FileOutputStream(navit_first_startup); fos_temp.write((int) info_popup_seen_count); // use to store info popup seen count fos_temp.flush(); fos_temp.close(); } } catch (Exception e) { e.printStackTrace(); } } /* * show info box for first time users */ // // ----------- info popup // ----------- info popup // ----------- info popup // ----------- info popup // intro_flag_info = false; if ((!info_popup_seen_count_end) && (startup_status == Navit_Status_NORMAL_STARTUP)) { intro_flag_info = true; } System.out.println("info_popup_seen_count=" + info_popup_seen_count); System.out.println("info_popup_seen_count_end=" + info_popup_seen_count_end + " intro_flag_info=" + intro_flag_info + " startup_status=" + startup_status); // make handler statically available for use in "msg_to_msg_handler" Navit_progress_h = this.progress_handler; // try // { // Navit.bigmap_bitmap = BitmapFactory.decodeResource(getResources(), R.raw.bigmap_colors_zanavi2); // } // catch (Exception e) // { // // when not enough memory is available, then disable large world overview map! // System.gc(); // Navit.bigmap_bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // } // // ------no----- // Navit.bigmap_bitmap.setDensity(120); // set our dpi!! try { setVolumeControlStream(AudioManager.STREAM_MUSIC); ActivityResults = new NavitActivityResult[16]; } catch (Exception e) { e.printStackTrace(); } try { NavitAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); } catch (Exception e) { e.printStackTrace(); } PowerManager pm = null; try { pm = (PowerManager) getSystemService(Context.POWER_SERVICE); } catch (Exception e) { e.printStackTrace(); } try { // -- // pm.wakeUp(SystemClock.uptimeMillis()); // -- // // **screen always full on** // wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "NavitDoNotDimScreen"); // **screen can go off, cpu will stay on** // wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "NavitDoNotDimScreen"); // this works so far, lets the screen dim, but it cpu and screen stays on wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "NavitDoNotDimScreen"); } catch (Exception e) { e.printStackTrace(); wl = null; } try { wl_cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ZANaviNeedCpu"); } catch (Exception e) { e.printStackTrace(); wl_cpu = null; } try { wl_navigating = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "ZANaviNavigationOn"); } catch (Exception e) { Log.e("Navit", "WakeLock NAV: create failed!!"); e.printStackTrace(); wl_navigating = null; } // try // { // if (wl_navigating != null) // { // wl_navigating.acquire(); // Log.e("Navit", "WakeLock NAV: acquire 00"); // } // } // catch (Exception e) // { // Log.e("Navit", "WakeLock NAV: something wrong 00"); // e.printStackTrace(); // } // try // { // if (wl != null) // { // try // { // wl.release(); // } // catch (Exception e2) // { // } // wl.acquire(); // Log.e("Navit", "WakeLock: acquire 1"); // } // } // catch (Exception e) // { // e.printStackTrace(); // } // -- extract overview maps -- // -- extract overview maps -- // File navit_worldmap2_file = new File(NAVIT_DATA_DIR + "/share/worldmap2.txt"); File navit_worldmap2_file = new File(MAP_FILENAME_PATH + "/worldmap2.txt"); if (!navit_worldmap2_file.exists()) { if (!extractRes("worldmap2", MAP_FILENAME_PATH + "/worldmap2.txt")) { Log.e("Navit", "Failed to extract worldmap2.txt"); } } File navit_worldmap5_file = new File(MAP_FILENAME_PATH + "/worldmap5.txt"); if (!navit_worldmap5_file.exists()) { if (!extractRes("worldmap5", MAP_FILENAME_PATH + "/worldmap5.txt")) { Log.e("Navit", "Failed to extract worldmap5.txt"); } } // -- extract overview maps -- // -- extract overview maps -- Log.e("Navit", "trying to extract language resource " + NavitTextTranslations.main_language + "_" + NavitTextTranslations.sub_language); if (!extractRes(NavitTextTranslations.main_language + "_" + NavitTextTranslations.sub_language, NAVIT_DATA_DIR + "/locale/" + NavitTextTranslations.main_language + "_" + NavitTextTranslations.sub_language + "/LC_MESSAGES/navit.mo")) { Log.e("Navit", "Failed to extract language resource " + NavitTextTranslations.main_language + "_" + NavitTextTranslations.sub_language); } Log.e("Navit", "trying to extract language resource " + NavitTextTranslations.main_language + "_" + NavitTextTranslations.sub_language.toLowerCase()); if (!extractRes( NavitTextTranslations.main_language + "_" + NavitTextTranslations.sub_language.toLowerCase(), NAVIT_DATA_DIR + "/locale/" + NavitTextTranslations.main_language + "_" + NavitTextTranslations.sub_language + "/LC_MESSAGES/navit.mo")) { Log.e("Navit", "Failed to extract language resource " + NavitTextTranslations.main_language + "_" + NavitTextTranslations.sub_language.toLowerCase()); } Log.e("Navit", "trying to extract language resource " + NavitTextTranslations.main_language); if (!extractRes(NavitTextTranslations.main_language, NAVIT_DATA_DIR + "/locale/" + NavitTextTranslations.main_language + "/LC_MESSAGES/navit.mo")) { Log.e("Navit", "Failed to extract language resource " + NavitTextTranslations.main_language); } // DEBUG - check if language file is on SDCARD - try { File debug_mo_src = new File("/sdcard/zanavi/debug/navit.mo"); File debug_mo_dest = new File( NAVIT_DATA_DIR + "/locale/" + NavitTextTranslations.main_language + "/LC_MESSAGES/navit.mo"); //* File navit_debug_dir = new File("/sdcard/zanavi/debug/"); //* navit_debug_dir.mkdirs(); copyFile(debug_mo_src, debug_mo_dest); } catch (Exception e) { e.printStackTrace(); } // DEBUG - check if language file is on SDCARD - File navit_config_xml_file = new File(NAVIT_DATA_SHARE_DIR + "/navit.xml"); if ((!navit_config_xml_file.exists()) || (NAVIT_ALWAYS_UNPACK_XMLFILE)) { xmlconfig_unpack_file = true; Log.e("Navit", "navit.xml does not exist, unpacking in any case"); } my_display_density = "mdpi"; // ldpi display (120 dpi) NavitGraphics.Global_want_dpi = Navit.metrics.densityDpi; NavitGraphics.Global_want_dpi_other = Navit.metrics.densityDpi; if (Navit.metrics.densityDpi <= 120) { my_display_density = "ldpi"; if (xmlconfig_unpack_file) { if (!extractRes("navitldpi", NAVIT_DATA_SHARE_DIR + "/navit.xml")) { Log.e("Navit", "Failed to extract navit.xml for ldpi device(s)"); } } } // mdpi display (160 dpi) else if ((Navit.metrics.densityDpi > 120) && (Navit.metrics.densityDpi <= 160)) { my_display_density = "mdpi"; if (xmlconfig_unpack_file) { if (!extractRes("navitmdpi", NAVIT_DATA_SHARE_DIR + "/navit.xml")) { Log.e("Navit", "Failed to extract navit.xml for mdpi device(s)"); } } } // hdpi display (240 dpi) else if ((Navit.metrics.densityDpi > 160) && (Navit.metrics.densityDpi < 320)) //else if (Navit.metrics.densityDpi == 240) { my_display_density = "hdpi"; if (xmlconfig_unpack_file) { if (!extractRes("navithdpi", NAVIT_DATA_SHARE_DIR + "/navit.xml")) { Log.e("Navit", "Failed to extract navit.xml for hdpi device(s)"); } } } // xhdpi display (320 dpi) else if (Navit.metrics.densityDpi >= 320) { // set the map display DPI down. otherwise everything will be very small and unreadable // and performance will be very low if (p.PREF_shrink_on_high_dpi) { NavitGraphics.Global_want_dpi = NavitGraphics.Global_Scaled_DPI_normal; } NavitGraphics.Global_want_dpi_other = NavitGraphics.Global_Scaled_DPI_normal; Log.e("Navit", "found xhdpi device, this is not fully supported yet"); Log.e("Navit", "using hdpi values for compatibility"); my_display_density = "hdpi"; if (xmlconfig_unpack_file) { if (!extractRes("navithdpi", NAVIT_DATA_SHARE_DIR + "/navit.xml")) { Log.e("Navit", "Failed to extract navit.xml for xhdpi device(s)"); } } } else { /* default, meaning we just dont know what display this is */ if (xmlconfig_unpack_file) { if (!extractRes("navitmdpi", NAVIT_DATA_SHARE_DIR + "/navit.xml")) { Log.e("Navit", "Failed to extract navit.xml (default version)"); } } } // Debug.startMethodTracing("calc"); int have_dpi = Navit.metrics.densityDpi; System.out.println("Global_want_dpi[001]=" + NavitGraphics.Global_want_dpi + ":" + Navit.metrics.densityDpi + ":" + NavitGraphics.Global_dpi_factor + ":" + NavitGraphics.Global_dpi_factor_better); if (NavitGraphics.Global_want_dpi == have_dpi) { NavitGraphics.Global_dpi_factor = 1; NavitGraphics.preview_coord_factor = 1; } else // this was missing??????!!!!!!!!!??????!!!!!! { NavitGraphics.Global_dpi_factor = ((float) NavitGraphics.Global_want_dpi / (float) have_dpi); NavitGraphics.preview_coord_factor = ((float) have_dpi / (float) NavitGraphics.Global_want_dpi); } System.out.println("Global_want_dpi[002]=" + NavitGraphics.Global_dpi_factor + ":" + NavitGraphics.preview_coord_factor); // gggggggggggggggggggggggggg new !!!!!!!!!!!!!!!!!!!! // --> dont use!! NavitMain(this, langu, android.os.Build.VERSION.SDK_INT); Log.e("Navit", "android.os.Build.VERSION.SDK_INT=" + Integer.valueOf(android.os.Build.VERSION.SDK)); // -- report share dir back to C-code -- //Message msg2 = new Message(); //Bundle b2 = new Bundle(); //b2.putInt("Callback", 82); //b2.putString("s", NAVIT_DATA_DIR + "/share/"); //msg2.setData(b2); //N_NavitGraphics.callback_handler.sendMessage(msg2); // -- report share dir back to C-code -- // -- report data dir back to C-code -- //msg2 = new Message(); //b2 = new Bundle(); //b2.putInt("Callback", 84); //b2.putString("s", NAVIT_DATA_DIR + "/"); //msg2.setData(b2); //N_NavitGraphics.callback_handler.sendMessage(msg2); // -- report share dir back to C-code -- draw_osd_thread = new drawOSDThread(); draw_osd_thread.start(); cwthr = new CWorkerThread(); cwthr.start(); // --new-- cwthr.StartMain(this, langu, Integer.valueOf(android.os.Build.VERSION.SDK), "" + Navit.metrics.densityDpi, NAVIT_DATA_DIR, NAVIT_DATA_SHARE_DIR); // --old-- // NavitMain(this, langu, Integer.valueOf(android.os.Build.VERSION.SDK), my_display_density); // --old-- // NavitActivity(3); // CAUTION: don't use android.os.Build.VERSION.SDK_INT if <uses-sdk android:minSdkVersion="3" /> // You will get exception on all devices with Android 1.5 and lower // because Build.VERSION.SDK_INT is since SDK 4 (Donut 1.6) // (see: http://developer.android.com/guide/appendix/api-levels.html) // Platform Version API Level // ============================================= // Android 4.0.3 15 // Android 4.0, 4.0.1, 4.0.2 14 // Android 3.2 13 // Android 3.1 12 // Android 3.0 11 // Android 2.3.3 10 // Android 2.3.1 9 // Android 2.2 8 // Android 2.1 7 // Android 2.0.1 6 // Android 2.0 5 // Android 1.6 4 // Android 1.5 3 // Android 1.1 2 // Android 1.0 1 Navit.mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); //try //{ // Thread.sleep(2000); //} //catch (InterruptedException e) //{ //} //getPrefs(); //activatePrefs(); // unpack some localized Strings // a test now, later we will unpack all needed strings for java, here at this point!! //String x = NavitGraphics.getLocalizedString("Austria"); //Log.e("Navit", "x=" + x); Navit.show_mem_used(); /* * GpsStatus.Listener listener = new GpsStatus.Listener() * { * public void onGpsStatusChanged(int event) * { * //System.out.println("xxxxx"); * if (event == GpsStatus.GPS_EVENT_SATELLITE_STATUS) * { * } * } * }; */ try { Intent sintent = new Intent(); sintent.setPackage("com.zoffcc.applications.zanavi_msg"); sintent.setAction("com.zoffcc.applications.zanavi_msg.ZanaviCloudService"); // ComponentName cname = startService(sintent); // Log.i("NavitPlugin", "start Service res=" + cname); // System.out.println("NavitPlugin:bind to Service"); boolean res_bind = bindService(sintent, serviceConnection, Context.BIND_AUTO_CREATE); // Log.i("NavitPlugin", "bind to Service res=" + res_bind); } catch (Exception e) { e.printStackTrace(); } // ------------- get all the flags for intro pages ------------- // ------------- get all the flags for intro pages ------------- // ------------- get all the flags for intro pages ------------- try { intro_flag_indexmissing = false; allow_use_index_search(); if (Navit_index_on_but_no_idx_files) { if (!NavitMapDownloader.download_active_start) { intro_flag_indexmissing = true; } } } catch (Exception e) { } try { intro_flag_nomaps = false; if (!have_maps_installed()) { if ((!NavitMapDownloader.download_active) && (!NavitMapDownloader.download_active_start)) { intro_flag_nomaps = true; } } } catch (Exception e) { } intro_flag_firststart = PreferenceManager.getDefaultSharedPreferences(this).getBoolean(PREF_KEY_FIRST_START, true); if (intro_flag_firststart) { intro_flag_update = false; } if (EasyPermissions.hasPermissions(this, perms)) { // have permissions! intro_flag_permissions = false; } else { // ask for permissions intro_flag_permissions = true; } // ------------- get all the flags for intro pages ------------- // ------------- get all the flags for intro pages ------------- // ------------- get all the flags for intro pages ------------- // -------------- INTRO -------------- // -------------- INTRO -------------- // -------------- INTRO -------------- intro_show_count = 0; // // -------------- INTRO -------------- // // -------------- INTRO -------------- // // -------------- INTRO -------------- // if (Navit.METHOD_DEBUG) Navit.my_func_name(1); }
From source file:com.example.sensingapp.SensingApp.java
public void recordSensingInfo(SensorData senData) { String sRecordLine;//from ww w . j a va 2 s. co m String sTimeField; Date dtCurDate; int i; long lStartTime = 0; long lCurrentTime = 0; SimpleDateFormat spdRecordTime, spdCurDateTime; final String DATE_FORMAT = "yyyyMMddHHmmss"; final String DATE_FORMAT_S = "yyMMddHHmmssSSS"; //"yyyyMMddHHmmssSSS" int nSensorReadingType = SENSOR_EVENT_NULL; int nSensorDataType; if (m_blnRecordStatus == false) { //Stopped return; } dtCurDate = new Date(); // Timestamp for the record spdRecordTime = new SimpleDateFormat(DATE_FORMAT_S); sTimeField = spdRecordTime.format(dtCurDate); nSensorDataType = senData.getSensorDataType(); if (nSensorDataType == DATA_TYPE_SENSOR) { SensorEvent event; event = senData.getSensorEvent(); synchronized (this) { switch (event.sensor.getType()) { case Sensor.TYPE_ACCELEROMETER: //X, Y, Z if (m_blnAcclEnabled) { m_sAccl = Float.toString(event.values[0]) + "," + Float.toString(event.values[1]) + "," + Float.toString(event.values[2]) + ","; nSensorReadingType = SENSOR_EVENT_ACCL; } // if (m_blnOrientEnabled) { // m_arrfAcclValues = event.values.clone(); // // if (calculateOrientation()) { // //Azimuth (rotation around z-axis); Pitch (rotation around x-axis), Roll (rotation around y-axis) // m_sOrient = Float.toString(m_arrfOrientValues[0]) + "," + // Float.toString(m_arrfOrientValues[1]) + "," + // Float.toString(m_arrfOrientValues[2]) + ","; // // nSensorReadingType = SENSOR_EVENT_ORIENT; // // } // } break; case Sensor.TYPE_LINEAR_ACCELERATION: //X,Y,Z if (m_blnLinearAcclEnabled) { m_sLinearAccl = Float.toString(event.values[0]) + "," + Float.toString(event.values[1]) + "," + Float.toString(event.values[2]) + ","; nSensorReadingType = SENSOR_EVENT_LINEAR_ACCL; } break; case Sensor.TYPE_GRAVITY: //X,Y,Z if (m_blnGravityEnabled) { m_sGravity = Float.toString(event.values[0]) + "," + Float.toString(event.values[1]) + "," + Float.toString(event.values[2]) + ","; nSensorReadingType = SENSOR_EVENT_GRAVITY; } break; case Sensor.TYPE_GYROSCOPE: //X,Y,Z m_sGyro = Float.toString(event.values[0]) + "," + Float.toString(event.values[1]) + "," + Float.toString(event.values[2]) + ","; nSensorReadingType = SENSOR_EVENT_GYRO; break; case Sensor.TYPE_MAGNETIC_FIELD: // Values are in micro-Tesla (uT) and measure the ambient magnetic field if (m_blnMagnetEnabled) { m_sMagnet = Float.toString(event.values[0]) + "," + Float.toString(event.values[1]) + "," + Float.toString(event.values[2]) + ","; nSensorReadingType = SENSOR_EVENT_MAGNET; } // if (m_blnOrientEnabled) { // m_arrfMagnetValues = event.values.clone(); // // if (calculateOrientation()) { // //Azimuth (rotation around z-axis); Pitch (rotation around x-axis), Roll (rotation around y-axis) // m_sOrient = Float.toString(m_arrfOrientValues[0]) + "," + // Float.toString(m_arrfOrientValues[1]) + "," + // Float.toString(m_arrfOrientValues[2]) + ","; // // if (nSensorReadingType != SENSOR_EVENT_MAGNET) { // nSensorReadingType = SENSOR_EVENT_ORIENT; // } // } // } break; case Sensor.TYPE_ROTATION_VECTOR: //Added on 20150910 if (m_blnOrientEnabled) { float[] arrfRotVal = new float[3]; float[] arrfR = new float[9]; float[] arrfValues = new float[3]; try { System.arraycopy(event.values, 0, arrfRotVal, 0, event.values.length); } catch (IllegalArgumentException e) { //Hardcode the size to handle a bug on Samsung devices System.arraycopy(event.values, 0, arrfRotVal, 0, 3); } SensorManager.getRotationMatrixFromVector(arrfR, arrfRotVal); SensorManager.getOrientation(arrfR, arrfValues); m_arrfOrientValues[0] = (float) Math.toDegrees(arrfValues[0]); m_arrfOrientValues[1] = (float) Math.toDegrees(arrfValues[1]); m_arrfOrientValues[2] = (float) Math.toDegrees(arrfValues[2]); if (m_arrfOrientValues[0] < 0) { m_arrfOrientValues[0] = m_arrfOrientValues[0] + 360; // Make Azimuth 0 ~ 360 } // //Azimuth (rotation around z-axis); Pitch (rotation around x-axis), Roll (rotation around y-axis) m_sOrient = Float.toString(m_arrfOrientValues[0]) + "," + Float.toString(m_arrfOrientValues[1]) + "," + Float.toString(m_arrfOrientValues[2]) + ","; //m_tvGpsUp.setText(m_sOrient); //Show orientation nSensorReadingType = SENSOR_EVENT_ORIENT; } break; case Sensor.TYPE_LIGHT: // Ambient light level in SI lux units m_sLight = Float.toString(event.values[0]) + ","; nSensorReadingType = SENSOR_EVENT_LIGHT; break; case Sensor.TYPE_PRESSURE: // Atmospheric pressure in hPa (millibar) m_sBarometer = Float.toString(event.values[0]) + ","; nSensorReadingType = SENSOR_EVENT_BAROMETER; break; } } } else if (nSensorDataType == DATA_TYPE_GPS) { Location locationGps; locationGps = senData.getGpsLocation(); if (locationGps != null) { m_location = new Location(locationGps); //Change from double to float m_sGPS = Float.valueOf((float) (locationGps.getLatitude())).toString() + "," + Float.valueOf((float) (locationGps.getLongitude())).toString() + ","; if (locationGps.hasAltitude()) { m_sGPS = m_sGPS + Float.valueOf((float) (locationGps.getAltitude())).toString() + ","; GeomagneticField geoField = new GeomagneticField( Double.valueOf(locationGps.getLatitude()).floatValue(), Double.valueOf(locationGps.getLongitude()).floatValue(), Double.valueOf(locationGps.getAltitude()).floatValue(), System.currentTimeMillis()); // Append Declination, in Degree m_sGPS = m_sGPS + Float.valueOf((float) (geoField.getDeclination())).toString() + "," + Float.valueOf((float) (geoField.getInclination())).toString() + ","; } else { m_sGPS = m_sGPS + ",,,"; //m_sGPS = m_sGPS + ","; } //New add 201408270009 if (locationGps.hasSpeed()) { m_sGPS = m_sGPS + Float.valueOf((float) (locationGps.getSpeed())).toString() + ","; } else { m_sGPS = m_sGPS + ","; } if (locationGps.hasBearing()) { m_sGPS = m_sGPS + Float.valueOf((float) (locationGps.getBearing())).toString() + ","; } else { m_sGPS = m_sGPS + ","; } nSensorReadingType = SENSOR_EVENT_GPS; m_blnGpsUp = true; show_screen5_GpsUp(); } else { m_blnGpsUp = false; show_screen5_GpsUp(); } } else if (nSensorDataType == DATA_TYPE_MIC) { double fSoundLevelDb; fSoundLevelDb = senData.getSoundLevelDb(); m_sSouldLevel = new BigDecimal(fSoundLevelDb).setScale(0, BigDecimal.ROUND_HALF_UP) + ","; nSensorReadingType = SENSOR_EVENT_MIC; } else if (nSensorDataType == DATA_TYPE_CELLULAR) { int nCellId; nCellId = senData.getCellId(); m_sCellId = Integer.valueOf(nCellId).toString() + ","; nSensorReadingType = SENSOR_EVENT_CELLULAR; } else if (nSensorDataType == DATA_TYPE_WIFI) { List<WifiData> lstWifiData = senData.getListWifiData(); int nWifiCnt = Math.min(WIFI_COUNT, lstWifiData.size()); m_sWifi = ""; for (i = 0; i < nWifiCnt; i++) { //m_sWifi = m_sWifi + lstWifiData.get(i).getSSID() + "," + lstWifiData.get(i).getBSSID() + "," + lstWifiData.get(i).getSignalLevel() + ","; m_sWifi = m_sWifi + lstWifiData.get(i).getBSSID() + "," + lstWifiData.get(i).getSignalLevel() + ","; } for (i = 1; i <= WIFI_COUNT - nWifiCnt; i++) { //m_sWifi = m_sWifi + ",,,"; m_sWifi = m_sWifi + ",,"; } nSensorReadingType = SENSOR_EVENT_WIFI; } if (nSensorReadingType == SENSOR_EVENT_NULL) { return; } sRecordLine = sTimeField + ","; if (m_blnNoLabel == false) { sRecordLine = sRecordLine + m_sCurrentLabel + ","; } sRecordLine = sRecordLine + Integer.valueOf(nSensorReadingType) + ","; //New: Every field always there //Field in each line: /* * 1) Timestamp * 2) Label * 3) SensingEventType * 4-6) Accl * 7-9) Linear Accl * 10-12) Gravity * 13-15) Gyro * 16-18) Orientation * 19-21) Magnet * 22) Light * 23) Barometer * 24) Sould Level (Decibel) * 25) Cell ID * 26-32) GPS (Lat, Long, Alt, Declination, Inclination, Speed, Bearing) * 33-72) WiFi (<BSSID, Level>) */ // sRecordLine = sRecordLine + m_sAccl + m_sGyro + m_sOrient + m_sMagnet + // m_sLight + m_sBarometer + // m_sSouldLevel + m_sCellId + // m_sGPS + m_sWifi; sRecordLine = sRecordLine + m_sAccl + m_sLinearAccl + m_sGravity + m_sGyro + m_sOrient + m_sMagnet + m_sLight + m_sBarometer + m_sSouldLevel + m_sCellId + m_sGPS + m_sWifi; //////////////////////////// // String sAngle = calculateRot(m_sAccl, m_sGravity); // String sarrAngle[] = sAngle.split(","); // String sShow = sarrAngle[0] + "\n" + sarrAngle[1]; // String sShow = ""; // if (m_sGravity.length() > 3) { // String sarrAngle[] = m_sGravity.split(","); // double fX = Double.valueOf(sarrAngle[0]).doubleValue(); // double fY = Double.valueOf(sarrAngle[1]).doubleValue(); // double fZ = Double.valueOf(sarrAngle[2]).doubleValue(); // // double fTotal = Math.sqrt(fX*fX + fY*fY + fZ*fZ); // // double fAngleZ = Math.acos(fZ/fTotal)/Math.PI*180; // double fAngleY = 90 - Math.acos(fY/fTotal)/Math.PI*180; // double fAngleX = 90 - Math.acos(fX/fTotal)/Math.PI*180; // // sShow = "X: " + fAngleX + "\n"; // sShow = sShow + "Y: " + fAngleY + "\n"; // sShow = sShow + "Z: " + fAngleZ; // // // } // if (m_sGravity.length() > 3) { // String sarrAngle[] = m_sGravity.split(","); // double fX = Double.valueOf(sarrAngle[0]).doubleValue(); // double fY = Double.valueOf(sarrAngle[1]).doubleValue(); // double fZ = Double.valueOf(sarrAngle[2]).doubleValue(); // // int nSymbol = 0; // if (fX < 0) { // sShow = sShow + "- X" + "\n"; // } else if (fX > 0) { // sShow = sShow + "+ X" + "\n"; // } // // if (fY < 0) { // sShow = sShow + "- Y" + "\n"; // } else if (fY > 0) { // sShow = sShow + "+ Y" + "\n"; // } // // if (fZ < 0) { // sShow = sShow + "- Z"; // } else if (fZ > 0) { // sShow = sShow + "+ Z"; // } // // } // // if (m_sGyro.length() > 3) { // String sarrAngle[] = m_sGyro.split(","); // double fX = Double.valueOf(sarrAngle[0]).doubleValue(); // double fY = Double.valueOf(sarrAngle[1]).doubleValue(); // double fZ = Double.valueOf(sarrAngle[2]).doubleValue(); // // int nSymbol = 0; // if (fX < 0) { // nSymbol = -1; // } else if (fX > 0) { // nSymbol = 1; // } // // if (fY < 0) { // nSymbol = nSymbol + (-1); // } else if (fY > 0) { // nSymbol = nSymbol + 1; // } // // if (fZ < 0) { // nSymbol = nSymbol + (-1); // } else if (fZ > 0) { // nSymbol = nSymbol + 1; // } // // if (nSymbol < 0) { // nSymbol = -1; // } else if (nSymbol > 0) { // nSymbol = 1; // } // // sShow = sShow + "\n\n" + nSymbol + ""; // } // m_tvSensingInfo.setText(sShow); //////////////////////////// sRecordLine = sRecordLine + System.getProperty("line.separator"); if (m_fwSensorRecord != null) { //Write information into file //Compose information into recordLine try { m_fwSensorRecord.write(sRecordLine); } catch (IOException e) { } } }