Home » Android » Android Core » Android Shake to Refresh tutorial

About Francesco Azzola

I'm a senior software engineer with more than 15 yrs old experience in JEE architecture. I'm SCEA certified (Sun Certified Enterprise Architect), SCWCD, SCJP. I'm an android enthusiast and i've worked for long time in the mobile development field.

Android Shake to Refresh tutorial

In this post we want to explore another way to refresh our app UI called Shake to Refresh. We all know the pull-to-refresh pattern that is implemented in several app. In this pattern we pull down our finger along the screen and the UI is refreshed:

android_pull_to_refresh4

Even this pattern is very useful, we can use another pattern to refresh our UI, based on smartphone sensors, we can call it Shake to refresh. Instead of pulling down our finger, we shake our smartphone to refresh the UI:

adroid_shake_to_refresh4

Implementation

In order to enable our app to support the Shake to refresh feature we have to use smartphone sensors and specifically motion sensors: Accelerometer. If you want to have more information how to use sensor you can give a look here.

As said, we want that the user shakes the smartphone to refresh and at the same time we don’t want that the refresh process starts accidentally or when user just moves his smartphone. So we have to implement some controls to be sure that the user is shaking the smartphone purposely. On the other hand we don’t want to implement this logic in the class that handles the UI, because it is not advisable to mix the UI logic with other things and using another class we can re-use this “pattern” in other contexts.

Then, we will create another class called ShakeEventManager. This class has to listen to sensor events:

public class ShakeEventManager implements SensorEventListener {
..
}

so that it will implement SensorEventListener. Then we have to look for the accelerometer sensor and register our class as event listener:

public void init(Context ctx) {
    sManager = (SensorManager)  ctx.getSystemService(Context.SENSOR_SERVICE);
    s = sManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    register();
}

and then:

public void register() {
    sManager.registerListener(this, s, SensorManager.SENSOR_DELAY_NORMAL);
}

To trigger the refresh event on UI some conditions must be verified, these conditions guarantee that the user is purposely shaking his smartphone. The conditions are:

  1. The acceleration must be greater than a threshold level
  2. A fixed number of acceleration events must occur
  3. The time between these events must be in a fixed time window

We will implement this logic in onSensorChanged method that is called everytime a new value is available. The first step is calculating the acceleration, we are interested to know the max acceleration value on the three axis and we want to clean the sensor value from the gravity force. So, as stated in the official Android documentation, we first apply a low pass filter to isolate the gravity force and then high pass filter:

private float calcMaxAcceleration(SensorEvent event) {
    gravity[0] = calcGravityForce(event.values[0], 0);
    gravity[1] = calcGravityForce(event.values[1], 1);
    gravity[2] = calcGravityForce(event.values[2], 2);

    float accX = event.values[0] - gravity[0];
    float accY = event.values[1] - gravity[1];
    float accZ = event.values[2] - gravity[2];

    float max1 = Math.max(accX, accY);
    return Math.max(max1, accZ);
}

where

// Low pass filter
private float calcGravityForce(float currentVal, int index) {
    return  ALPHA * gravity[index] + (1 - ALPHA) * currentVal;
}

Once we know the max acceleration we implement our logic:

@Override
public void onSensorChanged(SensorEvent sensorEvent) {
    float maxAcc = calcMaxAcceleration(sensorEvent);
    Log.d("SwA", "Max Acc ["+maxAcc+"]");
    if (maxAcc >= MOV_THRESHOLD) {
        if (counter == 0) {
            counter++;
            firstMovTime = System.currentTimeMillis();
            Log.d("SwA", "First mov..");
        } else {
            long now = System.currentTimeMillis();
            if ((now - firstMovTime) < SHAKE_WINDOW_TIME_INTERVAL)
                counter++;
            else {
                resetAllData();
                counter++;
                return;
            }
            Log.d("SwA", "Mov counter ["+counter+"]");

            if (counter >= MOV_COUNTS)
                if (listener != null)
                    listener.onShake();
        }
    }

}

Analyzing the code at line 3, we simply calculate the acceleration and then we check if it is greater than a threshold value  (condition 1) (line 5). If it is the first movement,  (line 7-8), we save the timestamp to check if other events happen in the specified time window. If all the conditions are satisfied we invoke a callback method define in the callback interface:

public static interface ShakeListener {
    public void onShake();
}

Test app

Now we have implemented the shake event manager we are ready to create a simple app that uses it. We can create a simple activity with a ListView that is refreshed when shake event occurs:

public class MainActivity extends ActionBarActivity implements ShakeEventManager.ShakeListener {
....

  @Override
    public void onShake() {
       // We update the ListView
    }
}

Where at line 5 we update the UI because this method is called only when the user is shaking his smartphone.

Some final considerations: When the app is paused we have to unregister the sensor listener so that it won’t listen anymore to events and in this way we will save the battery. On the other hand when the app is resumed we will register again the listener:

Override
protected void onResume() {
    super.onResume();
    sd.register();
}

@Override
protected void onPause() {
    super.onPause();
    sd.deregister();
}
Reference: Android Shake to Refresh tutorial from our JCG partner Francesco Azzola at the Surviving w/ Android blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

 

3 comments

  1. Very nice tutorial.Thanx for sharing…

  2. awesome tutorial for beginners.thanks for sharing.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


− three = 2

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Want to take your Java Skills to the next level?
Grab our programming books for FREE!
  • Save time by leveraging our field-tested solutions to common problems.
  • The books cover a wide range of topics, from JPA and JUnit, to JMeter and Android.
  • Each book comes as a standalone guide (with source code provided), so that you use it as reference.
Last Step ...

Where should we send the free eBooks?

Good Work!
To download the books, please verify your email address by following the instructions found on the email we just sent you.