public
class
SpeedometerActivity
extends
ActionBarActivity {
SensorManager sensors;
TextView tvSpeed;
float
velocity = 0f ;
float
currentAcceleration = 0f;
float
appliedAcceleration = 0f;
Date lastUpdated;
Handler handler =
null
;
Timer timer =
null
;
private
final
SensorEventListener sensorEventListener =
new
SensorEventListener(){
double
calibrator = Double.NaN;
@Override
public
void
onAccuracyChanged(Sensor sensor,
int
accuracy){
}
@SuppressWarnings
(
"deprecation"
)
@Override
public
void
onSensorChanged(SensorEvent event){
double
x = event.values[SensorManager.DATA_X];
double
y = event.values[SensorManager.DATA_Y];
double
z = event.values[SensorManager.DATA_Z];
double
a =
(-
1
)* Math.sqrt(Math.pow(x,
2
) + Math.pow(y,
2
) +
Math.pow(z,
2
));
if
(calibrator == Double.NaN){
calibrator =a;
}
else
{
computeVelocity();
currentAcceleration = (
float
)a;
}
}
};
@SuppressLint
(
"ServiceCast"
)
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_speedometer);
tvSpeed = (TextView)findViewById(R.id.text_meter);
lastUpdated =
new
Date(System.currentTimeMillis());
sensors =
(SensorManager)getSystemService(SEARCH_SERVICE);
sensors.registerListener(sensorEventListener,
sensors.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_FASTEST);
timer =
new
Timer(
"updateVelocity"
);
timer.scheduleAtFixedRate(
new
TimerTask(){
public
void
run(){
updateScreen();
}
},
0
,
1000
);
if
(savedInstanceState ==
null
) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container,
new
PlaceholderFragment()).commit();
}
}
@Override
public
boolean
onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.speedometer, menu);
return
true
;
}
@Override
public
boolean
onOptionsItemSelected(MenuItem item) {
int
id = item.getItemId();
if
(id == R.id.action_settings) {
return
true
;
}
return
super
.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public
static
class
PlaceholderFragment
extends
Fragment {
public
PlaceholderFragment() {
}
@Override
public
View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_speedometer,
container,
false
);
return
rootView;
}
}
private
void
computeVelocity(){
Date now =
new
Date(System.currentTimeMillis());
long
timeGap = now.getTime() - lastUpdated.getTime();
lastUpdated.setTime(now.getTime());
float
velocityGap = appliedAcceleration*(timeGap/
1000
);
appliedAcceleration = currentAcceleration;
velocity += velocityGap;
double
kmh =(Math.round(
100
*velocity*
3.6
)) /
100
;
tvSpeed.setText(String.valueOf(kmh) +
""
+
getString(R.string.speed_unit));
}
private
void
updateScreen(){
final
double
kmh = (Math.round(
100
* velocity *
3.6
)) /
100
;
handler.post(
new
Runnable(){
public
void
run(){
tvSpeed.setText(String.valueOf(kmh) +
" "
+ getString(R.string.speed_unit));
}
});
}
}