Untitled

 avatar
unknown
plain_text
3 years ago
14 kB
9
Indexable
package com.example.androidstudio.FittnessApp.ui.main.WindSurf;



import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import androidx.activity.OnBackPressedCallback;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.View;
import android.widget.ImageView;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.example.androidstudio.FittnessApp.R;



public class SurfFragment extends Fragment implements View.OnClickListener, LocationListener , SensorEventListener{
    private static final String TAG = "hsfWindFragment";
    private Button startBtn;
    private Button resBtn;
    ///
    Location lastloc;


    //*
    //****************************  compass


    ImageView compass_img;
    TextView txt_compass;
    int mAzimuth;
    private SensorManager mSensorManager;
    private Sensor mRotationV, mAccelerometer, mMagnetometer;
    boolean haveSensor = false, haveSensor2 = false;
    float[] rMat = new float[9];
    float[] orientation = new float[3];
    private float[] mLastAccelerometer = new float[3];
    private float[] mLastMagnetometer = new float[3];
    private boolean mLastAccelerometerSet = false;
    private boolean mLastMagnetometerSet = false;
    //***********************************End compass
    private TextView speed1 ;
    private TextView avkurs;
    private TextView averagespeed;
    private TextView weg;
    private TextView timepassed;
    private TextView kurs;


    private float speed2 ;
    double  wegtraveled = 0 ;

    private int sec = 0;
    private int sse = sec / 15 ;
    boolean timeStart = false;
    LocationManager locManager;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView():  ");

        View view = inflater.inflate(R.layout.surf_fragment, container, false);


        //***************************************** compass
        mSensorManager = (SensorManager)  getActivity().getSystemService(Context.SENSOR_SERVICE);

        compass_img = (ImageView) view.findViewById(R.id.img_compass);
        txt_compass = (TextView) view.findViewById(R.id.txt_azimuth);
        startcompass();

        //***********************************************************************************************************////******

        //*********************************************************************************************************************




        startBtn = (Button) view.findViewById(R.id.startbtn1);
        averagespeed = (TextView) view.findViewById(R.id.avaregespeedText);
        avkurs = (TextView)  view.findViewById(R.id.avaregespeedText);
        weg = (TextView) view.findViewById(R.id.destanceText);
        timepassed = (TextView) view.findViewById(R.id.durationsurf);
        resBtn = (Button) view.findViewById(R.id.resetbtn);
        speed1 = (TextView) view.findViewById(R.id.txtspeed);
        startBtn.setOnClickListener(this);
        resBtn.setOnClickListener(this);
        kurs = (TextView) view.findViewById(R.id.txt_azimuth);


        OnBackPressedCallback callback = new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                Log.d(TAG, "onBackPressed");
                AlertDialog.Builder backAlert = new AlertDialog.Builder(getActivity());
                backAlert.setTitle("Training Stop ?");
                backAlert.setMessage("would you like to stop surfing ?");
                backAlert.setPositiveButton("Yup", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Log.v(TAG, "going back to home");
                        NavHostFragment.findNavController(getParentFragment()).navigate(R.id.action_action_homeFragment_to_surfFragment_to_homeFragment);
                    }
                });

                backAlert.setNeutralButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });

                backAlert.show();
            }
        };
        requireActivity().getOnBackPressedDispatcher().addCallback(getActivity(), callback);

      //  startTimer();
        locManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

       // lastLoc = new Location();








        return view;
    }

   private void startTimer() {
        final Handler handler = new Handler();
        handler.post(new Runnable() {
            public void run() {
                int hours = sec / 3600;
                int mints = (sec % 3600) / 60;
                int secs = sec % 60;
                String time = String.format("%02d, %02d, %02d", hours, mints, secs);
                timepassed.setText(time);
                if(timeStart){


                    sec++;}


                handler.postDelayed(this, 1000);
            }


        });
    }
    //********************************compass
    public void startcompass() {
        if (mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR) == null) {
            if ((mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) == null) || (mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) == null)) {
                txt_compass.setText("no sensor");
            }
            else {
                mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
                mMagnetometer = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
                haveSensor = mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
                haveSensor2 = mSensorManager.registerListener(this, mMagnetometer, SensorManager.SENSOR_DELAY_UI);
            }
        }
        else{
            mRotationV = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
            haveSensor = mSensorManager.registerListener(this, mRotationV, SensorManager.SENSOR_DELAY_UI);
        }
    }
    public void stopCompass() {               // sensor
        if(haveSensor && haveSensor2){
            mSensorManager.unregisterListener(this,mAccelerometer);
            mSensorManager.unregisterListener(this,mMagnetometer);
        }
        else{
            if(haveSensor)
                mSensorManager.unregisterListener(this,mRotationV);
        }
    }

    private void stopSensor(){
       mSensorManager.unregisterListener(this, mAccelerometer);
       mSensorManager.unregisterListener(this, mMagnetometer);

    }



    @Override
    public void onLocationChanged(Location location) {
        if (timeStart) {
            Log.v(TAG, "onLocationChanged");
            getSpeed(location);
            getDistance(location);



        }
    }
    //******************************

    public void getSpeed(Location location) {
        speed2 = (location.getSpeed() * 3600 / 1000);
        String convertedSpeed = String.format("%.2f", speed2);
        speed1.setText(convertedSpeed);

    }


    public void onClick(View view){
        switch (view.getId()) {
            case R.id.startbtn1:
                Log.d(TAG, "onClick.startStop");
                if (timeStart == false) {
                    timeStart = true;
                    startBtn.setText("Stop");
                    startBtn.setBackgroundColor(Color.RED);
                    if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                        locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, SurfFragment.this);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////







////////////////////////////////////////////////////////////////////////////////////////////////////////////////


                        startcompass();//r

                    }

                } else {
                    timeStart = false;
                    startBtn.setText("Start");
                    startBtn.setBackgroundColor(Color.BLUE);
                    stopCompass();

                }
                break;

            case R.id.resetbtn:
                Log.d(TAG, "onClick.reset");
                AlertDialog.Builder resetAlert = new AlertDialog.Builder(getActivity());
                resetAlert.setTitle("reset?");
                resetAlert.setMessage("Are you SURE You want to reset ?");
                resetAlert.setPositiveButton("YUP", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Log.d(TAG, "reset all values");
                        resetall();
                        wegtraveled=0;

                        stopSensor();
                    }
                });

                resetAlert.setNeutralButton("Cancell", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });

                resetAlert.show();
                break;

        }
    }




    public void getDistance(Location userloc) {
        //ausrechnen der Distanz von der letzten location zur aktuellen location und addieren zur insgesamt zurückgelegten Distanz
        if(lastloc != null) {
          //  lastloc = new Location("");




            //c = currentLocation.getLatitude();
            //  d = currentLocation.getLongitude();




           //    wegtraveled += userloc.distanceTo(lastloc) / 100.0;

        }

        lastloc =new Location("");
        lastloc= userloc;


        //lastloc.setLatitude(0.0d);
       // lastloc.setLongitude(0.0d);
        wegtraveled = (CalculationByDistance( lastloc.getLatitude() , lastloc.getLongitude() ,userloc.getLatitude() , userloc.getLongitude() )) ;

        weg.setText("" + lastloc.getLatitude()+"" );








    }


    public double CalculationByDistance(double lat1, double lon1,
                                        double lat2, double lon2){

         final double DEG_RAD = 0.01745329251994;
         final double R_EARTH = 6367.45;

            double haversine, distance;
            double dLat, dLon;
            dLat = (lat2 - lat1) * DEG_RAD;
            dLon = (lon2 - lon1) * DEG_RAD;

            haversine = Math.sin(dLat * 0.5) * Math.sin(dLat * 0.5) +
                    Math.sin(dLon * 0.5) * Math.sin(dLon * 0.5) *
                            Math.cos(lat1 * DEG_RAD) *
                            Math.cos(lat2* DEG_RAD);

            distance = Math.asin(Math.sqrt(haversine)) * R_EARTH * 2.0;
            return distance;
        }



        //


    private void resetall() {

        timeStart = false;
        sec = 0;
        wegtraveled = 0;


        speed1.setText("0");
        weg.setText("0");

        averagespeed.setText("0");

        startBtn.setText("Start");
        startBtn.setBackgroundColor(Color.BLUE);
    }


    //******************************************compass
    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
            SensorManager.getRotationMatrixFromVector(rMat, event.values);
            mAzimuth = (int) (Math.toDegrees(SensorManager.getOrientation(rMat, orientation)[0]) + 360) % 360;
        }

        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            System.arraycopy(event.values, 0, mLastAccelerometer, 0, event.values.length);
            mLastAccelerometerSet = true;
        } else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
            System.arraycopy(event.values, 0, mLastMagnetometer, 0, event.values.length);
            mLastMagnetometerSet = true;
        }
        if (mLastAccelerometerSet && mLastMagnetometerSet) {
            SensorManager.getRotationMatrix(rMat, null, mLastAccelerometer, mLastMagnetometer);
            SensorManager.getOrientation(rMat, orientation);
            mAzimuth = (int) (Math.toDegrees(SensorManager.getOrientation(rMat, orientation)[0]) + 360) % 360;
        }

        mAzimuth = Math.round(mAzimuth);
        compass_img.setRotation(-mAzimuth);

        String where = "NW";

        if (mAzimuth >= 350 || mAzimuth <= 10)
            where = "N";
        if (mAzimuth < 350 && mAzimuth > 280)
            where = "NW";
        if (mAzimuth <= 280 && mAzimuth > 260)
            where = "W";
        if (mAzimuth <= 260 && mAzimuth > 190)
            where = "SW";
        if (mAzimuth <= 190 && mAzimuth > 170)
            where = "S";
        if (mAzimuth <= 170 && mAzimuth > 100)
            where = "SE";
        if (mAzimuth <= 100 && mAzimuth > 80)
            where = "E";
        if (mAzimuth <= 80 && mAzimuth > 10)
            where = "NE";


        txt_compass.setText(mAzimuth + "° " + where);
    }

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

    }


    //********************************************************
}