Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package simde608.cubecompanion.fragments;
- import android.app.Fragment;
- import android.app.FragmentTransaction;
- import android.content.Context;
- import android.content.SharedPreferences;
- import android.graphics.Color;
- import android.hardware.Sensor;
- import android.hardware.SensorEvent;
- import android.hardware.SensorEventListener;
- import android.hardware.SensorManager;
- import android.os.Bundle;
- import android.os.SystemClock;
- import android.util.Log;
- import android.view.LayoutInflater;
- import android.view.MotionEvent;
- import android.view.View;
- import android.view.ViewGroup;
- import android.widget.Button;
- import android.widget.CheckBox;
- import android.widget.Chronometer;
- import android.widget.SeekBar;
- import android.widget.TextView;
- import simde608.cubecompanion.MainActivity;
- import simde608.cubecompanion.R;
- import simde608.cubecompanion.database.DatabaseHandler;
- import simde608.cubecompanion.database.TimeEntry;
- /**
- * Created by Simon on 2014-05-06.
- */
- public class TimerFragment extends Fragment implements SensorEventListener, SeekBar.OnSeekBarChangeListener {
- /**
- * INFO:
- * This is the fragment that you use when taking the time.
- * There are several options and functions on this page.
- * You can stop the time using the accelerometer (by
- * bumping the table which the phone lays on) or
- * by pressing the button.
- * And there are several more options for you to
- * choose when done taking the time.
- */
- //Text to pass along to textfragment if helpButton is pressed.
- final static String HELP_TEXT = "+3:\n" +
- "If you solved the cube but had one step left you need to add three seconds." +
- "You can do this by pressing this button\n\n" +
- "Clear:\n" +
- "Remove current time, this is used for when you accidentally stopped or started the time, for example\n\n" +
- "DNF:\n" +
- "This stands for 'Did not finish', this is for having the cube at two or more steps left when stopping the time.\n\n" +
- "Share:\n" +
- "Share your last time with your friends\n\n" +
- "Use accelerometer:\n" +
- "If you check this box you can do the following:\n" +
- "Put the phone on a table, start the timer and when you have solved it you can slam the table" +
- "and the time stops this way. You can also set the sensitivity of the sensor.";
- final static float MY_SENSITIVITY_UNIT = 1 / (float) 1000;
- private DatabaseHandler db;
- private Chronometer timer;
- private TextView lastTime, textedLastTime, seekBarText;
- private double elapsedTimeMilliseconds, elapsedTime;
- private Button timerButton, plusThreeButton, clearButton, dnfButton, helpButton, shareButton;
- private Boolean timerOn, timerStandby;
- private SensorManager sensorManager;
- private SeekBar sensitivityCalibrator;
- private CheckBox accelerometerCheckBox;
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View view = inflater.inflate(R.layout.timer_fragment, container, false);
- elapsedTimeMilliseconds = 0;
- timerOn = false;
- timerStandby = false;
- assert view != null;
- timer = (Chronometer) view.findViewById(R.id.timer);
- lastTime = (TextView) view.findViewById(R.id.time); //This textView contains the time of your last solve.
- textedLastTime = (TextView) view.findViewById(R.id.yourTime); //This textview says either "Last time:" or "".
- accelerometerCheckBox = (CheckBox) view.findViewById(R.id.checkBox);
- //Database
- db = new DatabaseHandler(getActivity());
- //All buttons
- timerButton = (Button) view.findViewById(R.id.timerButton);
- plusThreeButton = (Button) view.findViewById(R.id.plusThree);
- clearButton = (Button) view.findViewById(R.id.clearButton);
- dnfButton = (Button) view.findViewById(R.id.DNF); //(Did not finish - button)
- helpButton = (Button) view.findViewById(R.id.helpButton);
- shareButton = (Button) view.findViewById(R.id.shareButton);
- sensitivityCalibrator = (SeekBar) view.findViewById(R.id.seekBar);
- sensitivityCalibrator.setOnSeekBarChangeListener(this);
- seekBarText = (TextView) view.findViewById(R.id.seekBarText);
- seekBarText.setText("Sensitivity: " + sensitivityCalibrator.getProgress());
- //If we create the fragment we need to set the text to nothing again.
- textedLastTime.setText("");
- //Set buttonClickListeners
- timerButton.setOnClickListener(
- new View.OnClickListener() {
- //If the time is ticking, button stops the time.
- //If the time is not running the button starts the time.
- //If you have just done a solve, button resets last time.
- @Override
- public void onClick(View v) {
- if(timerStandby && !timerOn){
- readyTimer();
- }
- else if(!timerOn){
- startTimer();
- }
- else if (timerOn){
- stopTimer();
- }
- }});
- plusThreeButton.setOnClickListener(
- new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- plusThree();
- }});
- clearButton.setOnClickListener(
- new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- clear();
- }});
- dnfButton.setOnClickListener(
- new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- didNotFinish();
- }});
- helpButton.setOnClickListener(
- new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- help();
- }});
- shareButton.setOnClickListener(
- new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- share();
- }
- });
- //This is to make it more clear that the button is being pressed down when you start the timer.
- timerButton.setOnTouchListener(new View.OnTouchListener() {
- @Override
- public boolean onTouch(View v, MotionEvent event) {
- switch(event.getAction()) {
- case MotionEvent.ACTION_DOWN:
- if(!timerOn && !timerStandby)
- timerButton.setBackgroundColor(Color.GREEN);
- break;
- case MotionEvent.ACTION_UP:
- timerButton.setBackgroundColor(Color.RED);
- break;
- }
- return false;
- }
- });
- sensorManager = (SensorManager)getActivity().getSystemService(Context.SENSOR_SERVICE);
- // Inflate the layout for this fragment
- return view;
- }
- @Override
- public void onSensorChanged(SensorEvent event) {
- if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER && timerOn) {
- getAccelerometer(event);
- }
- }
- int timesCollected = 0;
- float averageForce = 0;
- float currentAverage;
- boolean firstAverage = true;
- final int maxCollectedTimes = 3;
- final int maxCollectedTimesForFirstAverage = 14;
- //This is checking if accelerometer is getting repsonse and doing an action accordingly.
- private void getAccelerometer(SensorEvent event) {
- float zForce = event.values[2];
- timesCollected += 1;
- //Here we first calculate the average "Z" force for the specific phone.
- //It can differ on different devices.
- if(firstAverage){
- averageForce += zForce;
- if(timesCollected == maxCollectedTimesForFirstAverage){
- averageForce /= maxCollectedTimesForFirstAverage;
- Log.d("AVERAGEFORCE: ", String.valueOf(averageForce));
- timesCollected = 0;
- firstAverage = false;
- }
- }
- //When we have our average we can check when we rise over, or below this average, with an average of 3 times..
- else {
- currentAverage += zForce;
- double yourSensitivity = (10 - sensitivityCalibrator.getProgress()) * MY_SENSITIVITY_UNIT;
- double filtering = 0.04;
- if (timesCollected == maxCollectedTimes) {
- currentAverage /= maxCollectedTimes;
- double lowerBar = averageForce - yourSensitivity - filtering; //If the force is lower than this, stop time.
- double higherBar = averageForce + yourSensitivity + filtering; //If the force is higher than this, stop time.
- Log.d("FORCE: ", String.valueOf(currentAverage));
- if((currentAverage > higherBar || currentAverage < lowerBar) && accelerometerCheckBox.isChecked()){
- stopTimer();
- }
- timesCollected = 0;
- currentAverage = 0;
- }
- }
- }
- @Override
- public void onAccuracyChanged(Sensor sensor, int accuracy) {
- }
- @Override
- public void onResume() {
- super.onResume();
- // register this class as a listener for the orientation and
- // accelerometer sensors
- sensorManager.registerListener(this,
- sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
- SensorManager.SENSOR_DELAY_NORMAL);
- //Load checkbox status and sensitivity.
- loadCheckbox();
- loadSensitivity();
- }
- @Override
- public void onPause() {
- // unregister listener
- super.onPause();
- sensorManager.unregisterListener(this);
- //Save checkbox status and sensitivty
- save(accelerometerCheckBox.isChecked(), sensitivityCalibrator.getProgress());
- }
- public void readyTimer(){
- timerButton.setText("START");
- timerStandby = false;
- //Save the time if the time isn't 0!
- if(elapsedTime!=0){
- saveTime();
- }
- }
- public void startTimer(){
- timerButton.setText("STOP");
- timerOn = true;
- timer.setBase(SystemClock.elapsedRealtime());
- timer.start();
- }
- public void stopTimer(){
- timerButton.setText("SAVE");
- textedLastTime.setText("Last time: ");
- elapsedTimeMilliseconds = SystemClock.elapsedRealtime() - timer.getBase();
- //To get it in seconds, I divide by 1000.
- elapsedTime = elapsedTimeMilliseconds / (double) 1000;
- lastTime.setText(String.valueOf(elapsedTime) + "s");
- timerStandby = true;
- timerOn = false;
- timesCollected = 0;
- currentAverage = 0;
- averageForce = 0;
- firstAverage = true;
- timer.stop();
- }
- @Override
- public void onProgressChanged(SeekBar seekBar, int progress,
- boolean fromUser) {
- // change progress text label with current sensitivityCalibrator value
- seekBarText.setText("Sensitivity: "+progress);
- }
- @Override
- public void onStartTrackingTouch(SeekBar seekBar) {
- }
- @Override
- public void onStopTrackingTouch(SeekBar seekBar) {
- }
- //Button methods
- public void plusThree(){
- if(timerStandby){
- elapsedTime += 3;
- lastTime.setText(String.valueOf(elapsedTime) + "s");
- readyTimer();
- System.out.println("COUNT "+db.getEntryCount());
- }
- }
- public void clear(){
- if(timerStandby){
- elapsedTime = 0;
- lastTime.setText("Removed");
- readyTimer();
- }
- }
- public void didNotFinish(){
- //Instead of time, give the database a DNF.
- if(timerStandby){
- //-1 means DNF
- elapsedTime = -1;
- lastTime.setText("DNF");
- readyTimer();
- }
- }
- public void share(){
- //share with your friends if the timer is not on, and if we have a time to share.
- if(!timerOn && !lastTime.getText().toString().equals("") && !lastTime.getText().toString().equals("Removed")){
- //First, check if we got a token (is logged in)
- SharedPreferences userDetails = getActivity().getSharedPreferences("userdetails", Context.MODE_PRIVATE);
- String token = userDetails.getString("token", null);
- if(token == null){
- ((MainActivity)getActivity()).showGoogleAccountPicker();
- }
- //Then, check if our accesstoken is valid!
- else {
- Bundle bundle = new Bundle();
- bundle.putString("time", lastTime.getText().toString());
- PostTimeFragment frag = new PostTimeFragment();
- frag.setArguments(bundle);
- FragmentTransaction transaction = getFragmentManager().beginTransaction();
- transaction.replace(R.id.container, frag);
- transaction.addToBackStack(null);
- // Commit the transaction
- transaction.commit();
- }
- }
- }
- public void help(){
- //Go to new fragment explaining the buttons and features.
- Bundle bundle = new Bundle();
- bundle.putString("edttext", HELP_TEXT);
- TextFragment frag = new TextFragment();
- frag.setArguments(bundle);
- FragmentTransaction transaction = getFragmentManager().beginTransaction();
- transaction.replace(R.id.container, frag);
- transaction.addToBackStack(null);
- // Commit the transaction
- transaction.commit();
- }
- //So we dont need to change the checkbox and sensitivity every time we start the fragment.
- private void save(final boolean isChecked, final int sensitivityProgress) {
- SharedPreferences sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
- SharedPreferences.Editor editor = sharedPreferences.edit();
- editor.putBoolean("check", isChecked);
- editor.putInt("sensitivity", sensitivityProgress);
- editor.commit();
- }
- private void loadCheckbox() {
- SharedPreferences sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
- accelerometerCheckBox.setChecked(sharedPreferences.getBoolean("check", false));
- }
- private void loadSensitivity(){
- SharedPreferences sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
- sensitivityCalibrator.setProgress(sharedPreferences.getInt("sensitivity", 5));
- }
- public void saveTime(){
- db.addEntry(new TimeEntry(elapsedTime));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement