Advertisement
Guest User

Untitled

a guest
Aug 27th, 2014
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 15.22 KB | None | 0 0
  1. package simde608.cubecompanion.fragments;
  2.  
  3. import android.app.Fragment;
  4. import android.app.FragmentTransaction;
  5. import android.content.Context;
  6. import android.content.SharedPreferences;
  7. import android.graphics.Color;
  8. import android.hardware.Sensor;
  9. import android.hardware.SensorEvent;
  10. import android.hardware.SensorEventListener;
  11. import android.hardware.SensorManager;
  12. import android.os.Bundle;
  13. import android.os.SystemClock;
  14. import android.util.Log;
  15. import android.view.LayoutInflater;
  16. import android.view.MotionEvent;
  17. import android.view.View;
  18. import android.view.ViewGroup;
  19. import android.widget.Button;
  20. import android.widget.CheckBox;
  21. import android.widget.Chronometer;
  22. import android.widget.SeekBar;
  23. import android.widget.TextView;
  24.  
  25. import simde608.cubecompanion.MainActivity;
  26. import simde608.cubecompanion.R;
  27. import simde608.cubecompanion.database.DatabaseHandler;
  28. import simde608.cubecompanion.database.TimeEntry;
  29.  
  30.  
  31. /**
  32.  * Created by Simon on 2014-05-06.
  33.  */
  34. public class TimerFragment extends Fragment implements SensorEventListener, SeekBar.OnSeekBarChangeListener {
  35.  
  36.     /**
  37.      * INFO:
  38.      * This is the fragment that you use when taking the time.
  39.      * There are several options and functions on this page.
  40.      * You can stop the time using the accelerometer (by
  41.      * bumping the table which the phone lays on) or
  42.      * by pressing the button.
  43.      * And there are several more options for you to
  44.      * choose when done taking the time.
  45.      */
  46.  
  47.     //Text to pass along to textfragment if helpButton is pressed.
  48.     final static String HELP_TEXT = "+3:\n" +
  49.             "If you solved the cube but had one step left you need to add three seconds." +
  50.             "You can do this by pressing this button\n\n" +
  51.             "Clear:\n" +
  52.             "Remove current time, this is used for when you accidentally stopped or started the time, for example\n\n" +
  53.             "DNF:\n" +
  54.             "This stands for 'Did not finish', this is for having the cube at two or more steps left when stopping the time.\n\n" +
  55.             "Share:\n" +
  56.             "Share your last time with your friends\n\n" +
  57.             "Use accelerometer:\n" +
  58.             "If you check this box you can do the following:\n" +
  59.             "Put the phone on a table, start the timer and when you have solved it you can slam the table" +
  60.             "and the time stops this way. You can also set the sensitivity of the sensor.";
  61.  
  62.  
  63.     final static float MY_SENSITIVITY_UNIT = 1 / (float) 1000;
  64.  
  65.     private DatabaseHandler db;
  66.     private Chronometer timer;
  67.     private TextView lastTime, textedLastTime, seekBarText;
  68.     private double elapsedTimeMilliseconds, elapsedTime;
  69.     private Button timerButton, plusThreeButton, clearButton, dnfButton, helpButton, shareButton;
  70.     private Boolean timerOn, timerStandby;
  71.     private SensorManager sensorManager;
  72.     private SeekBar sensitivityCalibrator;
  73.  
  74.     private CheckBox accelerometerCheckBox;
  75.  
  76.     @Override
  77.     public View onCreateView(LayoutInflater inflater, ViewGroup container,
  78.                              Bundle savedInstanceState) {
  79.         View view = inflater.inflate(R.layout.timer_fragment, container, false);
  80.         elapsedTimeMilliseconds = 0;
  81.         timerOn = false;
  82.         timerStandby = false;
  83.  
  84.         assert view != null;
  85.         timer = (Chronometer) view.findViewById(R.id.timer);
  86.         lastTime = (TextView) view.findViewById(R.id.time);             //This textView contains the time of your last solve.
  87.         textedLastTime = (TextView) view.findViewById(R.id.yourTime);   //This textview says either "Last time:" or "".
  88.         accelerometerCheckBox = (CheckBox) view.findViewById(R.id.checkBox);
  89.  
  90.         //Database
  91.         db = new DatabaseHandler(getActivity());
  92.  
  93.         //All buttons
  94.         timerButton = (Button) view.findViewById(R.id.timerButton);
  95.         plusThreeButton = (Button) view.findViewById(R.id.plusThree);
  96.         clearButton = (Button) view.findViewById(R.id.clearButton);
  97.         dnfButton = (Button) view.findViewById(R.id.DNF);   //(Did not finish - button)
  98.         helpButton = (Button) view.findViewById(R.id.helpButton);
  99.         shareButton = (Button) view.findViewById(R.id.shareButton);
  100.  
  101.         sensitivityCalibrator = (SeekBar) view.findViewById(R.id.seekBar);
  102.         sensitivityCalibrator.setOnSeekBarChangeListener(this);
  103.         seekBarText = (TextView) view.findViewById(R.id.seekBarText);
  104.         seekBarText.setText("Sensitivity: " + sensitivityCalibrator.getProgress());
  105.  
  106.         //If we create the fragment we need to set the text to nothing again.
  107.         textedLastTime.setText("");
  108.  
  109.  
  110.         //Set buttonClickListeners
  111.         timerButton.setOnClickListener(
  112.                 new View.OnClickListener() {
  113.                     //If the time is ticking, button stops the time.
  114.                     //If the time is not running the button starts the time.
  115.                     //If you have just done a solve, button resets last time.
  116.                     @Override
  117.                     public void onClick(View v) {
  118.                         if(timerStandby && !timerOn){
  119.                             readyTimer();
  120.                         }
  121.                         else if(!timerOn){
  122.                             startTimer();
  123.                         }
  124.                         else if (timerOn){
  125.                             stopTimer();
  126.                         }
  127.                     }});
  128.  
  129.         plusThreeButton.setOnClickListener(
  130.                 new View.OnClickListener() {
  131.                     @Override
  132.                     public void onClick(View v) {
  133.                         plusThree();
  134.                     }});
  135.  
  136.         clearButton.setOnClickListener(
  137.                 new View.OnClickListener() {
  138.                     @Override
  139.                     public void onClick(View v) {
  140.                         clear();
  141.                     }});
  142.  
  143.         dnfButton.setOnClickListener(
  144.                 new View.OnClickListener() {
  145.                     @Override
  146.                     public void onClick(View v) {
  147.                         didNotFinish();
  148.                     }});
  149.  
  150.         helpButton.setOnClickListener(
  151.                 new View.OnClickListener() {
  152.                     @Override
  153.                     public void onClick(View v) {
  154.                         help();
  155.                     }});
  156.  
  157.         shareButton.setOnClickListener(
  158.                 new View.OnClickListener() {
  159.                     @Override
  160.                     public void onClick(View v) {
  161.                         share();
  162.                     }
  163.                 });
  164.  
  165.         //This is to make it more clear that the button is being pressed down when you start the timer.
  166.         timerButton.setOnTouchListener(new View.OnTouchListener() {
  167.             @Override
  168.             public boolean onTouch(View v, MotionEvent event) {
  169.                 switch(event.getAction()) {
  170.                     case MotionEvent.ACTION_DOWN:
  171.                         if(!timerOn && !timerStandby)
  172.                         timerButton.setBackgroundColor(Color.GREEN);
  173.                         break;
  174.                     case MotionEvent.ACTION_UP:
  175.                         timerButton.setBackgroundColor(Color.RED);
  176.                         break;
  177.                 }
  178.                 return false;
  179.             }
  180.         });
  181.         sensorManager = (SensorManager)getActivity().getSystemService(Context.SENSOR_SERVICE);
  182.  
  183.  
  184.         // Inflate the layout for this fragment
  185.         return view;
  186.     }
  187.  
  188.     @Override
  189.     public void onSensorChanged(SensorEvent event) {
  190.         if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER && timerOn) {
  191.             getAccelerometer(event);
  192.         }
  193.  
  194.     }
  195.  
  196.     int timesCollected = 0;
  197.     float averageForce = 0;
  198.     float currentAverage;
  199.     boolean firstAverage = true;
  200.     final int maxCollectedTimes = 3;
  201.     final int maxCollectedTimesForFirstAverage = 14;
  202.     //This is checking if accelerometer is getting repsonse and doing an action accordingly.
  203.     private void getAccelerometer(SensorEvent event) {
  204.         float zForce = event.values[2];
  205.         timesCollected += 1;
  206.         //Here we first calculate the average "Z" force for the specific phone.
  207.         //It can differ on different devices.
  208.         if(firstAverage){
  209.             averageForce += zForce;
  210.             if(timesCollected == maxCollectedTimesForFirstAverage){
  211.                 averageForce /= maxCollectedTimesForFirstAverage;
  212.                 Log.d("AVERAGEFORCE: ", String.valueOf(averageForce));
  213.                 timesCollected = 0;
  214.                 firstAverage = false;
  215.             }
  216.         }
  217.         //When we have our average we can check when we rise over, or below this average, with an average of 3 times..
  218.         else {
  219.             currentAverage += zForce;
  220.             double yourSensitivity = (10 - sensitivityCalibrator.getProgress()) * MY_SENSITIVITY_UNIT;
  221.             double filtering = 0.04;
  222.             if (timesCollected == maxCollectedTimes) {
  223.                 currentAverage /= maxCollectedTimes;
  224.                 double lowerBar = averageForce - yourSensitivity - filtering;   //If the force is lower than this, stop time.
  225.                 double higherBar = averageForce + yourSensitivity + filtering;  //If the force is higher than this, stop time.
  226.                 Log.d("FORCE: ", String.valueOf(currentAverage));
  227.                 if((currentAverage > higherBar || currentAverage < lowerBar) && accelerometerCheckBox.isChecked()){
  228.                     stopTimer();
  229.                 }
  230.                 timesCollected = 0;
  231.                 currentAverage = 0;
  232.             }
  233.         }
  234.     }
  235.  
  236.     @Override
  237.     public void onAccuracyChanged(Sensor sensor, int accuracy) {
  238.     }
  239.  
  240.     @Override
  241.     public void onResume() {
  242.         super.onResume();
  243.         // register this class as a listener for the orientation and
  244.         // accelerometer sensors
  245.         sensorManager.registerListener(this,
  246.                 sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
  247.                 SensorManager.SENSOR_DELAY_NORMAL);
  248.         //Load checkbox status and sensitivity.
  249.         loadCheckbox();
  250.         loadSensitivity();
  251.     }
  252.  
  253.     @Override
  254.     public void onPause() {
  255.         // unregister listener
  256.         super.onPause();
  257.         sensorManager.unregisterListener(this);
  258.         //Save checkbox status and sensitivty
  259.         save(accelerometerCheckBox.isChecked(), sensitivityCalibrator.getProgress());
  260.     }
  261.  
  262.     public void readyTimer(){
  263.         timerButton.setText("START");
  264.         timerStandby = false;
  265.         //Save the time if the time isn't 0!
  266.         if(elapsedTime!=0){
  267.             saveTime();
  268.         }
  269.     }
  270.  
  271.     public void startTimer(){
  272.         timerButton.setText("STOP");
  273.         timerOn = true;
  274.         timer.setBase(SystemClock.elapsedRealtime());
  275.         timer.start();
  276.     }
  277.  
  278.     public void stopTimer(){
  279.         timerButton.setText("SAVE");
  280.         textedLastTime.setText("Last time:  ");
  281.         elapsedTimeMilliseconds = SystemClock.elapsedRealtime() - timer.getBase();
  282.         //To get it in seconds, I divide by 1000.
  283.         elapsedTime = elapsedTimeMilliseconds / (double) 1000;
  284.         lastTime.setText(String.valueOf(elapsedTime) + "s");
  285.         timerStandby = true;
  286.         timerOn = false;
  287.         timesCollected = 0;
  288.         currentAverage = 0;
  289.         averageForce = 0;
  290.         firstAverage = true;
  291.         timer.stop();
  292.     }
  293.  
  294.     @Override
  295.     public void onProgressChanged(SeekBar seekBar, int progress,
  296.                                   boolean fromUser) {
  297.         // change progress text label with current sensitivityCalibrator value
  298.         seekBarText.setText("Sensitivity: "+progress);
  299.     }
  300.  
  301.     @Override
  302.     public void onStartTrackingTouch(SeekBar seekBar) {
  303.  
  304.     }
  305.  
  306.     @Override
  307.     public void onStopTrackingTouch(SeekBar seekBar) {
  308.  
  309.     }
  310.  
  311.  
  312.     //Button methods
  313.     public void plusThree(){
  314.         if(timerStandby){
  315.             elapsedTime += 3;
  316.             lastTime.setText(String.valueOf(elapsedTime) + "s");
  317.             readyTimer();
  318.             System.out.println("COUNT "+db.getEntryCount());
  319.         }
  320.     }
  321.  
  322.     public void clear(){
  323.         if(timerStandby){
  324.             elapsedTime = 0;
  325.             lastTime.setText("Removed");
  326.             readyTimer();
  327.         }
  328.     }
  329.  
  330.     public void didNotFinish(){
  331.         //Instead of time, give the database a DNF.
  332.         if(timerStandby){
  333.             //-1 means DNF
  334.             elapsedTime = -1;
  335.             lastTime.setText("DNF");
  336.             readyTimer();
  337.         }
  338.     }
  339.  
  340.     public void share(){
  341.         //share with your friends if the timer is not on, and if we have a time to share.
  342.         if(!timerOn && !lastTime.getText().toString().equals("") && !lastTime.getText().toString().equals("Removed")){
  343.             //First, check if we got a token (is logged in)
  344.             SharedPreferences userDetails = getActivity().getSharedPreferences("userdetails", Context.MODE_PRIVATE);
  345.             String token = userDetails.getString("token", null);
  346.             if(token == null){
  347.                 ((MainActivity)getActivity()).showGoogleAccountPicker();
  348.             }
  349.             //Then, check if our accesstoken is valid!
  350.             else {
  351.                 Bundle bundle = new Bundle();
  352.                 bundle.putString("time", lastTime.getText().toString());
  353.                 PostTimeFragment frag = new PostTimeFragment();
  354.                 frag.setArguments(bundle);
  355.                 FragmentTransaction transaction = getFragmentManager().beginTransaction();
  356.                 transaction.replace(R.id.container, frag);
  357.                 transaction.addToBackStack(null);
  358.                 // Commit the transaction
  359.                 transaction.commit();
  360.             }
  361.         }
  362.     }
  363.  
  364.     public void help(){
  365.         //Go to new fragment explaining the buttons and features.
  366.         Bundle bundle = new Bundle();
  367.         bundle.putString("edttext", HELP_TEXT);
  368.         TextFragment frag = new TextFragment();
  369.         frag.setArguments(bundle);
  370.         FragmentTransaction transaction = getFragmentManager().beginTransaction();
  371.         transaction.replace(R.id.container, frag);
  372.         transaction.addToBackStack(null);
  373.         // Commit the transaction
  374.         transaction.commit();
  375.     }
  376.  
  377.     //So we dont need to change the checkbox and sensitivity every time we start the fragment.
  378.     private void save(final boolean isChecked, final int sensitivityProgress) {
  379.         SharedPreferences sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
  380.         SharedPreferences.Editor editor = sharedPreferences.edit();
  381.         editor.putBoolean("check", isChecked);
  382.         editor.putInt("sensitivity", sensitivityProgress);
  383.         editor.commit();
  384.     }
  385.  
  386.     private void loadCheckbox() {
  387.         SharedPreferences sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
  388.         accelerometerCheckBox.setChecked(sharedPreferences.getBoolean("check", false));
  389.     }
  390.  
  391.     private void loadSensitivity(){
  392.         SharedPreferences sharedPreferences = getActivity().getPreferences(Context.MODE_PRIVATE);
  393.         sensitivityCalibrator.setProgress(sharedPreferences.getInt("sensitivity", 5));
  394.     }
  395.  
  396.     public void saveTime(){
  397.         db.addEntry(new TimeEntry(elapsedTime));
  398.     }
  399. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement