Skip to content

Instantly share code, notes, and snippets.

@ssaurel
Last active May 18, 2017 11:54
Show Gist options
  • Save ssaurel/77f6bae3aa5a8dc1e84f64878fc9d595 to your computer and use it in GitHub Desktop.
Save ssaurel/77f6bae3aa5a8dc1e84f64878fc9d595 to your computer and use it in GitHub Desktop.
Simulate ambient temperature for the Thermometer Tutorial on the SSaurel's Channel
package com.ssaurel.mythermometer;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
private Thermometer thermometer;
private float temperature;
private Timer timer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
thermometer = (Thermometer) findViewById(R.id.thermometer);
}
@Override
protected void onResume() {
super.onResume();
simulateAmbientTemperature();
}
@Override
protected void onPause() {
super.onPause();
unregisterAll();
}
private void simulateAmbientTemperature() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
temperature = Utils.randInt(-10, 35);
runOnUiThread(new Runnable() {
@Override
public void run() {
thermometer.setCurrentTemp(temperature);
getSupportActionBar().setTitle(getString(R.string.app_name) + " : " + temperature);
}
});
}
}, 0, 3500);
}
private void unregisterAll() {
timer.cancel();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment