it.flaviomascetti.posture.AccuracyTestFragment.java Source code

Java tutorial

Introduction

Here is the source code for it.flaviomascetti.posture.AccuracyTestFragment.java

Source

package it.flaviomascetti.posture;

/*
*    Copyright 2015 - 2016 Flavio Mascetti
*
*    This file is part of Posture.
*
*    Posture is free software: you can redistribute it and/or modify
*    it under the terms of the GNU General Public License as published by
*    the Free Software Foundation, either version 3 of the License, or
*    (at your option) any later version.
*
*    Posture is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU General Public License for more details.
*
*    You should have received a copy of the GNU General Public License
*    along with Posture.  If not, see <http://www.gnu.org/licenses/>
*/

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

public class AccuracyTestFragment extends Fragment implements SensorEventListener {

    private SensorManager sensorManager;
    private Sensor accelerometer;

    private final int numberOfDimensions = 3; // default value of Cartesian coordinates dimensions
    private final int delayTestStart = 7000; // delay of 7 seconds

    private boolean testInProgress = false; // says if the accuracy test has begun

    private double actualValues[] = new double[numberOfDimensions];
    // contains the actual accelerometer values
    private double previousValues[]; // contains the previous accelerometer values
    private double minDiff[]; // lowest difference between values

    private SharedPreferences sp;
    private SharedPreferences.Editor editor;

    private Button button;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.accuracy_test_fragment, viewGroup, false);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        sp = getActivity().getSharedPreferences("saved_preferences", Context.MODE_PRIVATE);

        sensorManager = (SensorManager) getActivity().getApplicationContext()
                .getSystemService(Context.SENSOR_SERVICE);
        accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

    }

    @Override
    public void onStart() {
        super.onStart();

        button = (Button) getActivity().findViewById(R.id.button_accuracy_test);

        button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // Showing the start snackbar
                Snackbar.make(getActivity().findViewById(R.id.fragment_accuracy_test), R.string.snack_begin_test,
                        Snackbar.LENGTH_LONG).show();

                testInProgress = false;

                // Delayed start of function testStart
                Handler handler = new Handler();
                handler.postDelayed(beginTest, delayTestStart);

                // Make the Begin Button unclickable
                button.setEnabled(false);
            }
        });

        // set reset button onClick
        getActivity().findViewById(R.id.button_accuracy_reset).setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                getActivity().getSharedPreferences("saved_preferences", Context.MODE_PRIVATE).edit().clear()
                        .apply();
                updateOldResults();
            }
        });

        // set share button onClick
        getActivity().findViewById(R.id.button_accuracy_share).setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT,
                        String.format(android.os.Build.MODEL + "\n\nx: %f\ny: %f\nz: %f",
                                sp.getFloat("saved_x_values", 10), sp.getFloat("saved_y_values", 10),
                                sp.getFloat("saved_z_values", 10)));
                sendIntent.setType("text/plain");
                startActivity(sendIntent);
            }
        });
    }

    public void onResume() {
        super.onResume();

        updateOldResults();
    }

    public void onPause() {
        super.onPause();

        sensorManager.unregisterListener(this);
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

    private Runnable beginTest = new Runnable() {
        @Override
        public void run() {

            // Two beep to notify the start
            ToneGenerator sound = new ToneGenerator(AudioManager.STREAM_MUSIC, 85);
            sound.startTone(ToneGenerator.TONE_PROP_BEEP, 500);

            // Keep the screen on
            getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

            // Beginning accelerometer tracking
            sensorManager.registerListener(AccuracyTestFragment.this, accelerometer,
                    SensorManager.SENSOR_DELAY_FASTEST);

            // Delayed start of function completeTest
            Handler handler = new Handler();
            handler.postDelayed(stopTest, 10000);
        }
    };

    @Override
    public void onSensorChanged(SensorEvent event) {
        if (testInProgress) {
            // Obtaining accelerations
            for (int i = 0; i < numberOfDimensions; i++)
                actualValues[i] = event.values[i];

            for (int i = 0; i < numberOfDimensions; i++) {
                if (Math.abs(actualValues[i] - previousValues[i]) > 0)
                    if (minDiff[i] > Math.abs(actualValues[i] - previousValues[i]))
                        minDiff[i] = Math.abs(actualValues[i] - previousValues[i]);
            }

            System.arraycopy(actualValues, 0, previousValues, 0, numberOfDimensions);
        } else {
            testInProgress = true;
            previousValues = new double[] { 0, 0, 0 };
            minDiff = new double[] { 10, 10, 10 };
            actualValues = new double[] { 0, 0, 0 };
        }
    }

    private Runnable stopTest = new Runnable() {
        @Override
        public void run() {
            // Stopping accelerometer tracking
            sensorManager.unregisterListener(AccuracyTestFragment.this);

            Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
            vibrator.vibrate(700);

            // Stopping screen on keeping
            getActivity().getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

            testInProgress = false;

            button.setEnabled(true);

            editor = sp.edit();

            if (sp.getBoolean("saved_values", false)) {
                if (sp.getFloat("saved_x_values", 10) > minDiff[0])
                    editor.putFloat("saved_x_values", (float) minDiff[0]);
                if (sp.getFloat("saved_y_values", 10) > minDiff[1])
                    editor.putFloat("saved_y_values", (float) minDiff[1]);
                if (sp.getFloat("saved_z_values", 10) > minDiff[2])
                    editor.putFloat("saved_z_values", (float) minDiff[2]);
            } else {
                editor.putBoolean("saved_values", true);
                editor.putFloat("saved_x_values", (float) minDiff[0]);
                editor.putFloat("saved_y_values", (float) minDiff[1]);
                editor.putFloat("saved_z_values", (float) minDiff[2]);
            }
            editor.apply();
            updateOldResults();
        }
    };

    void updateOldResults() {
        if (sp.getBoolean("saved_values", false)) {
            TextView txt = (TextView) getActivity().findViewById(R.id.text_view_accuracy);
            txt.setText(String.format("x: %f\ny: %f\nz: %f", sp.getFloat("saved_x_values", 10),
                    sp.getFloat("saved_y_values", 10), sp.getFloat("saved_z_values", 10)));
            button.setText(R.string.redo_accuracy_test);
            getActivity().findViewById(R.id.text_view_accuracy_header).setVisibility(View.VISIBLE);
            txt.setVisibility(TextView.VISIBLE);
            getActivity().findViewById(R.id.button_accuracy_share).setVisibility(View.VISIBLE);
            getActivity().findViewById(R.id.button_accuracy_reset).setVisibility(View.VISIBLE);
            getActivity().findViewById(R.id.text_view_accuracy_how).setVisibility(TextView.INVISIBLE);
        } else {
            getActivity().findViewById(R.id.button_accuracy_share).setVisibility(View.INVISIBLE);
            getActivity().findViewById(R.id.button_accuracy_reset).setVisibility(View.INVISIBLE);
            button.setText(R.string.begin_accuracy_test);
            getActivity().findViewById(R.id.text_view_accuracy_header).setVisibility(View.INVISIBLE);
            getActivity().findViewById(R.id.text_view_accuracy).setVisibility(TextView.INVISIBLE);
            getActivity().findViewById(R.id.text_view_accuracy_how).setVisibility(TextView.VISIBLE);
        }
    }
}