Mikke Kenneth
Mikke Kenneth

Reputation: 11

Delaying a task in Android

I'm receiving acceleration values from an external kit with my Smartphone. My primary goal is to detect a fall, and I'm using following algorithm to achieve this:

// Method to be triggered, when data is received over BLE interface
public void onCharacteristicChanged(BluetoothGattCharacteristic c) {
    data = parse(c);
}

public T getData() {
    return data;
}


@Override
public String getDataString() {
    final float[] data = getData();
    return TiSensorUtils.coordinatesToString(data);
}

@Override
public float[] parse(final BluetoothGattCharacteristic c) {    
    Integer x = c.getIntValue(FORMAT_SINT8, 0);
    Integer y = c.getIntValue(FORMAT_SINT8, 1);
    Integer z = c.getIntValue(FORMAT_SINT8, 2);

    double X = x / 64.0;
    double Y = y / 64.0;
    double Z = -1 * z / 64.0;
    double G = Math.sqrt((X * X) + (Y * Y) + (Z * Z));
    double L = 1;                 

    if ((G > 1.3 || G < 0.7) && timerStatus.equals("OFF"))
    {           
        // I WANT THE DELAY HERE !!!!!!!!
        if ((Z < -0.9 && Z > -1.1 || (Z < 1.1 && Z > 0.9)) && (X < 0.3 && X > -0.3) && (Y < 0.3 && Y > -0.3))
        {
            cdt = new accCountDownTimer(4000, 1000);
            cdt.start();
            timerStatus = "ON";
            return new float[]{(float)X, (float)Y, (float)Z, (float)G, (float)L};                   
        }
    }       
        return new float[]{(float)X, (float)Y, (float)Z, (float)G};                 
}

I want a kind of task delay function just after the first "if" statement, but since I don't want to block the thread, Thread.Sleep(2000) will be useless in this case. I have succesfully implemented a corresponding algorithm in C#, where I used Task.delay(2000) for this purpose. Is there a similar method in java ?.

Upvotes: 0

Views: 91

Answers (2)

TootsieRockNRoll
TootsieRockNRoll

Reputation: 3288

use

new Handler().postDelayed(Runnable, delaytime);

updated answer:

you might want to do this

new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            data = parse(c);
        }
    }, delayMillis);

Upvotes: 1

Don Chakkappan
Don Chakkappan

Reputation: 7560

    snoozeTimer.
    schedule(new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    onSnoozeTimerExpiry();
                }
            });
        }
    }, snoozeDuration);

Upvotes: 2

Related Questions