Android Service not notifying it has started and UI Locking Intermittently

398 views Asked by At

I get the issue intermittently, It seems when the UI locks the Service notification has NOT popped up, however the service is running. I assume it is a thread issue locking I have managed to grab a small portion of the crash, but will have to wait for another to try to grab the entire log. the error was:

PID: 20841
    Reason: Input dispatching timed out (a336dd com.app/com.DefineRouteActivity (server) is not responding. Waited 5001ms for FocusEvent(hasFocus=false))
    Parent: com.app/.navigation.DefineRouteActivity
    Load: 2.78 / 1.97 / 1.69
    ----- Output from /proc/pressure/memory -----
    some avg10=0.00 avg60=0.00 avg300=0.00 total=117026127
    full avg10=0.00 avg60=0.00 avg300=0.00 total=23878171
    ----- End output from /proc/pressure/memory -----
    
    CPU usage from 0ms to 7967ms later (2021-04-22 11:29:33.154 to 2021-04-22 11:29:41.121):
      23% 1615/system_server: 13% user + 10% kernel / faults: 10015 minor 615 major
      15% 1299/adbd: 4.1% user + 11% kernel / faults: 2 minor
      14% 20841/com.app: 11% user + 3.2% kernel / faults: 6343 minor 63 major
      10% 624/logd: 4.5% user + 6.4% kernel / faults: 1 minor
      9.1% 1044/[email protected]: 4.8% user + 4.2% kernel / faults: 175 minor
      8.4% 438/mmc-cmdqd/0: 0% user + 8.4% kernel
      7.5% 19662/logcat: 2% user + 5.5% kernel

My Service is as below, there is considerable code that is unused or not relevant but i thought it wise to share the whole file, I am starting the service in a background thread or so i thought but have now confirmed it is actually running in main, however the UI is not always blocked?

package com.app.motionGetter;

@RequiresApi(api = Build.VERSION_CODES.O)
public class SensorService extends Service implements SensorEventListener, Serializable {

    public static int eventNumber = 0;
    public static int strap;
    private static boolean isMagConsistentAtInit;
    private static final String TAG = "SensorService";
    public static float newDir;
    public static double newtestAzimuth;
    private Looper serviceLooper;
    public static ServiceHandler serviceHandler;
    public static HandlerThread serviceThread;
    private static double previousTime;
    private static double previousGyroTime;
    public static int OSStepCount = 0;

    public final static short TYPE_ACCELEROMETER = Sensor.TYPE_ACCELEROMETER;
    public final static short TYPE_GRAVITY = Sensor.TYPE_GRAVITY;
    public final static short TYPE_GYROSCOPE = Sensor.TYPE_GYROSCOPE;
    //public final static short TYPE_GYROSCOPE_UNCALIBRATED = Sensor.TYPE_GYROSCOPE_UNCALIBRATED;
    public final static short TYPE_MAGNETIC = Sensor.TYPE_MAGNETIC_FIELD;
    public final static short TYPE_PRESSURE = Sensor.TYPE_PRESSURE;
    public final static short TYPE_AMBIENT_TEMPERATURE = Sensor.TYPE_AMBIENT_TEMPERATURE; //Not available do checks
    public final static short TYPE_ROTATION_VECTOR = Sensor.TYPE_ROTATION_VECTOR;
    //public final static short TYPE_STEP_DETECTOR = Sensor.TYPE_STEP_DETECTOR;
    public static Location currentLocation;
    private final Executor IMUExecutor = Executors.newFixedThreadPool(2);
    CalibrationSimpleWalkManager calibrationSimpleWalkManager = new CalibrationSimpleWalkManager();

    private static final int SCREEN_OFF_RECEIVER_DELAY = 100;

    //10ms minimum due to Android/hardware limitations 9 gives more accurate 10ms intervals
    private final short POLL_FREQUENCY = 9;

    private SensorManager wSensorManager = null;
    private PowerManager.WakeLock wakeLock = null;
    private ExecutorService executor;
    //private Sensor sensor;
    private Sensor accelerometer;
    private Sensor gyroscope;
    private Sensor gyroscopeUncalibrated;
    private Sensor pressure;
    private Sensor magnetic;
    private Sensor gravity;
    //Test
    private Sensor rotationVector;
    private Sensor stepDetect;
    //private Sensor temperature;
    private NotificationManager manager;
    public static double landscapePhoneHeading;
    public static double portraitPhoneHeading;
    public static boolean filterRequired;

    public static float[] mGravity;
    public static float[] mGeomagnetic;

    //TEST
    private float[] mValuesAccelerometer;
    private float[] mValuesMagneticField;
    private float[] mMatrixR;
    private float[] mMatrixI;
    private float[] mMatrixValues;

    //Data Method
    public static boolean sensorPollThroughPut;
    public static int sampleNumber;
    public static int uniqueID;

    //IMUData Capture
    public static ArrayList<ImuData> imuDataCapture = new ArrayList<ImuData>();


    //TEST
    private static float[] accelerometerMatrix = new float[3];
    private static float[] gyroscopeMatrix = new float[3];
    private static float[] pressureMatrix = new float[1];
    public static float[] magneticMatrix = new float[3];
    private static float[] accelInGMatrix = new float[3];
    public static float[] gravityMatrix = new float[3];
    private static float[] temperatureMatrix = new float[1];
    private static float[] gyroscopeMatrixUncalibrated = new float[6];
    private LongToDoubleFunction longToDoubleFunction;
    private static long curTime;
    private double tHeading;
    SharedPreferences defaultPreferences = PreferenceManager.getDefaultSharedPreferences(MyApplication.getAppContext());

    public static final float ALPHAPASS = 1 / 16f;

    static CLibrary lib = Native.loadLibrary("com.app.t", CLibrary.class);
    private float bearing;

    private final class ServiceHandler extends Handler {
        public ServiceHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void registerListener() {
        wSensorManager.registerListener(this, accelerometer, 10000, 0, serviceHandler);
        wSensorManager.registerListener(this, gyroscope, 10000, 0, serviceHandler);
        wSensorManager.registerListener(this, pressure, 10000, 0, serviceHandler);
        wpSensorManager.registerListener(this, magnetic, 10000, 0, serviceHandler);
        wSensorManager.registerListener(this, gravity, 10000, 0, serviceHandler);
        //Test
        wSensorManager.registerListener(this, rotationVector, 10000, 0, serviceHandler);
        //wSensorManager.registerListener(this, stepDetect, 10000, 0, serviceHandler);
        if (logUncalibratedGyro) {
            //wSensorManager.registerListener(this, gyroscopeUncalibrated, 10000, 0, serviceHandler);
        }
        Logging.append_log_line(INFO, "sensor,accelerometer", accelerometer.getName());
        Logging.append_log_line(INFO, "sensor,gyroscope", gyroscope.getName());
        Logging.append_log_line(INFO, "sensor,pressure", pressure.getName());
        Logging.append_log_line(INFO, "sensor,magnetic", magnetic.getName());
        Logging.append_log_line(INFO, "sensor,gravity", gravity.getName());

    }

    private void unregisterListener() {
        wSensorManager.unregisterListener(this);
    }

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        @Override
        public void onReceive(Context context, Intent intent) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                Log.i(TAG, "onReceive(" + intent + ")");
            }
            if (!Objects.equals(intent.getAction(), Intent.ACTION_SCREEN_OFF)) {
                return;
            }

            Runnable runnable = new Runnable() {
                @RequiresApi(api = Build.VERSION_CODES.O)
                public void run() {
                    Log.i(TAG, "Runnable executing...");
                    unregisterListener();
                    registerListener();
                }
            };

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                new Handler().postDelayed(runnable, SCREEN_OFF_RECEIVER_DELAY);
            }
        }
    };


    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        if (sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
            MagneticAccuracy = accuracy;
        }

    }

    protected static float[] LowPassFilter(float[] output, float[] input) {
        if (output == null) return input;
        for (int i = 0; i < input.length; i++) {
            output[i] = output[i] + ALPHAPASS * (input[i] - output[i]);
        }
        return output;
    }


    private static double last_compass_reading = -1000;
    private static int last_stap_status = -100;

    @RequiresApi(api = Build.VERSION_CODES.O)
    public static double getCalculatedCompassHeading(SensorEvent event) {
        //Test
        double PI = Math.PI;
        double TWO_PI = PI * 2;
        float in[] = new float[9];
        float out[] = new float[9];
        float[] rMtarix = new float[9];
        float[] orientation = new float[3];
        float[] portOrientation = new float[3];

        SensorManager.getRotationMatrixFromVector(rMtarix, event.values);
        SensorManager.getOrientation(rMtarix, orientation);

        GeomagneticField geomagneticFieldx = null;
        geomagneticFieldx = new GeomagneticField(
                (float) currentLocation.getLatitude(),
                (float) currentLocation.getLongitude(),
                (float) currentLocation.getAltitude(),
                System.currentTimeMillis());

        double testHeading = mod(orientation[0] + TWO_PI, TWO_PI);
        testHeading = (Math.toDegrees(testHeading) + geomagneticFieldx.getDeclination());
        if (last_compass_reading != testHeading) {
            last_compass_reading = testHeading;
        }

        //For Landscape
        return testHeading;

    }

    //Portrait Heading
    @RequiresApi(api = Build.VERSION_CODES.O)
    public static double getCalculatedPortraitHeading(SensorEvent event) {
        //Test
        double PI = Math.PI;
        double TWO_PI = PI * 2;
        float in[] = new float[9];
        float out[] = new float[9];
        float[] rMtarix = new float[9];
        float[] orientation = new float[3];
        float[] portOrientation = new float[3];

        SensorManager.getRotationMatrixFromVector(rMtarix, event.values);
        SensorManager.getOrientation(rMtarix, orientation);

        SensorManager.remapCoordinateSystem(rMtarix, SensorManager.AXIS_X, SensorManager.AXIS_Z, out);
        SensorManager.getOrientation(out, portOrientation);
        double portHeading = Math.toDegrees(portOrientation[0]);

        GeomagneticField geomagneticFieldx = null;
        geomagneticFieldx = new GeomagneticField(
                (float) currentLocation.getLatitude(),
                (float) currentLocation.getLongitude(),
                (float) currentLocation.getAltitude(),
                System.currentTimeMillis());

        portHeading += geomagneticFieldx.getDeclination();

        if(portHeading<0){
            portHeading = 360+portHeading;
        }
        Log.d(TAG, "getCalculatedCompassHeading: portheading "+portHeading);
        return portHeading;

    }

    private static Boolean lastSensorsRequired = false;
    private static Boolean lastPollSensorsRequired = false;

    @RequiresApi(api = Build.VERSION_CODES.O)
    public void onSensorChanged(SensorEvent event) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            globalEvent = event;
            if (sensorsRequired != lastSensorsRequired) {
                lastSensorsRequired = sensorsRequired;

            }
            Log.d(TAG, "[DOUBLECHECK] onSensorChanged: SENSORS REQ " + sensorsRequired);
            if (sensorsRequired) {
                curTime = SystemClock.elapsedRealtimeNanos();
                //Remove Gravity
                if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
                    accelerometerMatrix = event.values;
                } else if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
                    magneticMatrix = event.values;
                    globalMagEvent = event;
                } else if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
                    gyroscopeMatrix = event.values;
                } else if (event.sensor.getType() == Sensor.TYPE_GRAVITY) {
                    gravityMatrix = event.values;
                } else if (event.sensor.getType() == Sensor.TYPE_PRESSURE) {
                    pressureMatrix = event.values;
                } else if (event.sensor.getType() == Sensor.TYPE_AMBIENT_TEMPERATURE) {
                    temperatureMatrix = event.values;
                } else if (logUncalibratedGyro) {
                    if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE_UNCALIBRATED) {
                        gyroscopeMatrixUncalibrated = event.values;
                    }
                }

                accelInGMatrix[0] = accelerometerMatrix[0] / 9.81f;
                accelInGMatrix[1] = accelerometerMatrix[1] / 9.81f;
                accelInGMatrix[2] = accelerometerMatrix[2] / 9.81f;

                longToDoubleFunction = l -> l;

                double time = event.timestamp / 1000000000.0000000;/*longToDoubleFunction.applyAsDouble(curTime)*/
                Log.d(TAG, "[DOUBLECHECK] onSensorChanged: POLLSENSORS REQ " + pollSensorsRequired);
                if (isRunning) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        if (filterRequired) {
                            if ((time * 1000) >= ((previousTime * 1000) + 10)) {
                                buildIMUEvent(magneticMatrix, accelInGMatrix, gyroscopeMatrix, pressureMatrix, time, gyroscopeMatrixUncalibrated);
                                previousTime = time;
                            }
                        } else {
                            buildIMUEvent(magneticMatrix, accelInGMatrix, gyroscopeMatrix, pressureMatrix, time, gyroscopeMatrixUncalibrated);
                        }
                    }
                }


                if (event.sensor.getType() == Sensor.TYPE_STEP_DETECTOR) {
                    OSStepCount++;
                    Logging.append_log_line(INFO, "OS Step Count", String.valueOf(OSStepCount));
                }

  
                if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
                    globalEvent = event;
                    mGeomagnetic = event.values;
                }
                if (event.sensor.getType() == Sensor.TYPE_GRAVITY) {
                    globalEvent = event;
                    mGravity = event.values;
                }
            }
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
                landscapePhoneHeading = getCalculatedCompassHeading(event);
                portraitPhoneHeading = getCalculatedPortraitHeading(event);
            }
        }

      
    }

    static double mod(double a, double b) {
        return a % b;
    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onCreate() {
        super.onCreate();

        currentLocation = calibrationSimpleWalkManager.getCurrentLocation();
        previousTime = 0.0;
        previousGyroTime = 0.0;

        serviceThread = new HandlerThread("ServiceStart",
                THREAD_PRIORITY_BACKGROUND);
        serviceThread.start();

        // Get the HandlerThread's Looper and use it for our Handler
        serviceLooper = serviceThread.getLooper();
        serviceHandler = new ServiceHandler(serviceLooper);

        startMyOwnForeground();

        wSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        assert wSensorManager != null;

        accelerometer = wSensorManager.getDefaultSensor(TYPE_ACCELEROMETER);
        gyroscope = wSensorManager.getDefaultSensor(TYPE_GYROSCOPE);
        pressure = wSensorManager.getDefaultSensor(TYPE_PRESSURE);
        magnetic = wSensorManager.getDefaultSensor(TYPE_MAGNETIC);
        gravity = wSensorManager.getDefaultSensor(TYPE_GRAVITY);
        //Test
        rotationVector = wSensorManager.getDefaultSensor(TYPE_ROTATION_VECTOR);
        //stepDetect = wSensorManager.getDefaultSensor(TYPE_STEP_DETECTOR);
        if (logUncalibratedGyro) {
            //gyroscopeUncalibrated = wSensorManager.getDefaultSensor(TYPE_GYROSCOPE_UNCALIBRATED);
        }
        PowerManager wManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        assert wManager != null;
        wakeLock = wManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Application:TAG");

        registerReceiver(receiver, new IntentFilter(Intent.ACTION_SCREEN_OFF));

        executor = Executors.newSingleThreadExecutor();
    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startMyOwnForeground() {
        String NOTIFICATION_CHANNEL_ID = "com.app";
        String channelName = "SensorService";
        NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_MIN);
        chan.setLightColor(Color.BLUE);
        chan.setSound(null, null);
        chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
        manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        assert manager != null;
        manager.createNotificationChannel(chan);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
        @SuppressLint("ResourceAsColor") Notification notification = notificationBuilder.setOngoing(true)
                .setContentTitle("sensors are running in background")
                .setPriority(NotificationManager.IMPORTANCE_MIN)
                .setSmallIcon(android.R.drawable.ic_menu_mylocation)
                .setColor(Color.GRAY)
                .setCategory(Notification.CATEGORY_SERVICE)
                .build();
        startForeground(2, notification);
    }


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        //For creating the Foreground Service
        startMyOwnForeground();

        imuDataCapture.clear();
        sampleNumber = 1;
        Date date = new Date();
        String dateString = DateFormat.getDateTimeInstance().format(date);
        uniqueID = Math.abs(dateString.hashCode());
        wSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        if (wSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) != null) {
            // Success! There's a magnetometer.
            Log.d(TAG, "there is mag");
        } else {
            // Failure! No magnetometer.
            Log.d(TAG, "there is no mag");
        }

        if (wSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null) {
            // Success! There's a magnetometer.
            Log.d(TAG, "there is accel-uncal");
        } else {
            // Failure! No magnetometer.
            Log.d(TAG, "there is no accel-uncal");
        }

        if (wSensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE) != null) {
            // Success! There's a magnetometer.
            Log.d(TAG, "there is TEMP");
        } else {
            // Failure! No magnetometer.
            Log.d(TAG, "there is no TEMP");
        }

        if (wSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE) != null) {
            // Success! There's a magnetometer.
            Log.d(TAG, "there is GYRO-UNCAL");
        } else {
            // Failure! No magnetometer.
            Log.d(TAG, "there is no GYRO-UNCAL");
        }

        if (wSensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE) != null) {
            // Success! There's a magnetometer.
            Log.d(TAG, "there is PRESSURE");
        } else {
            // Failure! No magnetometer.
            Log.d(TAG, "there is no PRESSURE");
        }

        registerListener();
        // wakeLock.acquire();
        sensorServiceIsRunning = true;

        return START_NOT_STICKY;
    }

    public void stopSensorThread() {
        Handler stopHandler = new Handler(serviceThread.getLooper());
        stopHandler.post(new Runnable() {
            @Override
            public void run() {
                unregisterReceiver(receiver);
                unregisterListener();
            }
        });
        serviceThread.quit();
    }

    @Override
    public void onDestroy() {

        Log.d(TAG, "onDestroy()");
        serviceHandler.removeCallbacksAndMessages(serviceLooper);

        //Unregister receiver and listener prior to executor shutdown
        unregisterReceiver(receiver);
        unregisterListener();

        manager.cancel(2);
        //Prevent new tasks from being added to thread
        executor.shutdown();

        last_stap_status = -100;

        Log.d(TAG, "Executor shutdown is called");

        //Create new thread to wait for executor to clear queue and wait for termination
        new Thread(new Runnable() {
            public void run() {
                try {
                    //Wait for all tasks to finish before we proceed
                    while (!executor.awaitTermination(1, TimeUnit.SECONDS)) {
                        Log.i(TAG, "Waiting for current tasks to finish");
                    }
                    Log.i(TAG, "No queue to clear");
                } catch (InterruptedException e) {
                    Log.e(TAG, "Exception caught while waiting for finishing executor tasks" + "thread: " + Thread.currentThread().getName());
                    executor.shutdownNow();
                    Thread.currentThread().interrupt();
                }

                if (executor.isTerminated()) {
                    //Stop everything else once the task queue is clear
                    //wakeLock.release();
                    stopForeground(true);
                    stopSelf();
                }
            }
        }).start();

        sensorServiceIsRunning = false;

        stopSensorThread();

        IMUExecutor.execute(() -> {
            tempCSVList = imuDataCapture;
            writeIMUCSV();
            IMUDatabase imuDatabase = IMUDatabase.getInstance(MyApplication.getAppContext());
            imuDatabase.imuDao().insertAll(imuDataCapture);
        });

    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public void buildIMUEvent(float[] magneticMatrix, float[] accelerometerMatrix, float[] gyroscopeMatrix, float[] pressureMatrix, /*float[] temperatureMatrix,*/ double curTime, float[] gyroscopeMatrixUncalibrated) {

        TCIMUEvent mTCIMUEvent = new TCIMUEvent();
        mTCIMUEvent.setAccelValid(true);
        mTCIMUEvent.setGyroValid(true);
        mTCIMUEvent.setMagValid(true);
        mTCIMUEvent.setPressureValid(true);
        mTCIMUEvent.setTemperatureValid(true);
        mTCIMUEvent.setMag(magneticMatrix);
        mTCIMUEvent.setAccel(accelerometerMatrix);
        mTCIMUEvent.setGyro(gyroscopeMatrix);
        mTCIMUEvent.setPressure((pressureMatrix[0]/10));
        /*mTCIMUEvent.setTemperature(temperatureMatrix[0]);*/
        mTCIMUEvent.setTime(curTime);
        //mTCIMUEvent.setTime((SystemClock.uptimeMillis()/1000.00));

        callHandleImuEvent(mTCIMUEvent);


    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public void callHandleImuEvent(TCIMUEvent tcimuEvent) {

        int x = tcimuEvent.getMag().length;
        double[] ac = new double[tcimuEvent.getAccel().length];
        for (int i = 0; i < tcimuEvent.getAccel().length; i++) {
            ac[i] = (double) tcimuEvent.getAccel()[i];
        }
        double[] mg = new double[tcimuEvent.getMag().length];
        for (int i = 0; i < tcimuEvent.getMag().length; i++) {
            mg[i] = (double) tcimuEvent.getMag()[i];
        }
        double[] gy = new double[tcimuEvent.getGyro().length];
        for (int i = 0; i < tcimuEvent.getGyro().length; i++) {
            gy[i] = (double) tcimuEvent.getGyro()[i];
        }

        double[] acTrimmed = {ac[0], ac[1], ac[2]};
        double[] mgTrimmed = {mg[0], mg[1], mg[2]};
        double[] gyTrimmed = {gy[0], gy[1], gy[2]};


        int statusHC = 0;
        double userheading = 0;
        int rotationModeHC = RotationMode.Undetermined;

        IntByReference status = new IntByReference(statusHC);
        DoubleByReference heading = new DoubleByReference(userheading);
        IntByReference rotationMode = new IntByReference(rotationModeHC);

        CLibrary.imuDataSample_t.ByReference imuDataSample = new CLibrary.imuDataSample_t.ByReference();

        imuDataSample.accel = acTrimmed;
        imuDataSample.mag = mgTrimmed;
        imuDataSample.gyro = gyTrimmed;


        double[] testac = imuDataSample.accel;
        double[] testmg = imuDataSample.mag;
        double[] testgy = imuDataSample.gyro;
        imuDataSample.accelValid = 1;
        if (isInitialzied == true) {
            imuDataSample.magValid = 1;
        } else {
            imuDataSample.magValid = 1;
        }
        imuDataSample.gyroValid = 1;
        imuDataSample.pressure = (tcimuEvent.pressure / 10);
        imuDataSample.pressureValid = 1;
        imuDataSample.temperature = tcimuEvent.temperature;
        imuDataSample.temperatureValid = 1;
        imuDataSample.time = tcimuEvent.time;
        lib.HandleImuEvent(imuDataSample, status, heading, rotationMode);

        TManager.imuUdateSent = true;
        strap = status.getValue();
        if (last_stap_status != strap) {
            if (strap == 1) {
                Intent intent = new Intent(MyApplication.getAppContext(), TInitialisedReceiver.class);
                MyApplication.getAppContext().sendBroadcast(intent);
            }
            Log.d(TAG, "callHandleImuEvent: StrapStatus CHANGED TO: " + strap);
            last_stap_status = strap;
        }
        tHeading = heading.getValue();
        switch (strap) {
            case 1:
                isInitialzied = true;
                isMagConsistentAtInit = true;
                break;
            case 2:
                isInitialzied = true;
                isMagConsistentAtInit = false;
                break;
            default:
                int y = 0;
                break;
        }

    }


    private boolean bridgeData(SensorEvent event) {
        float[] accelerometerMatrix = new float[3];
        float[] gyroscopeMatrix = new float[3];
        float[] magneticMatrix = new float[3];
        float[] gravityMatrix = new float[3];
        float[] pressureMatrix = new float[1];

        switch (event.sensor.getType()) {
            case Sensor.TYPE_MAGNETIC_FIELD:
                magneticMatrix[0] = event.values[0];
                magneticMatrix[1] = event.values[1];
                magneticMatrix[2] = event.values[2];
                break;
            case Sensor.TYPE_ACCELEROMETER:
                accelerometerMatrix[0] = event.values[0];
                accelerometerMatrix[1] = event.values[1];
                accelerometerMatrix[2] = event.values[2];
                break;
            case Sensor.TYPE_GYROSCOPE:
                gyroscopeMatrix[0] = event.values[0];
                gyroscopeMatrix[1] = event.values[1];
                gyroscopeMatrix[2] = event.values[2];
                break;
            case Sensor.TYPE_PRESSURE:
                pressureMatrix[0] = event.values[0];
                break;
            case Sensor.TYPE_GRAVITY:
                gravityMatrix[0] = event.values[0];
                gravityMatrix[1] = event.values[1];
                gravityMatrix[2] = event.values[2];
                break;
            default:
                return false;
        }


        return true;
    }

}

Hopefully someone can advise me if the threading is correct and shed some light on the issue being experienced

0

There are 0 answers