To create an app which is sensitive to shake event:
A. In manifest - register a boot receiver. It will make sure your app will always be activated
after device restart:
<receiver android:name=".OnBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
B. Create a shake event listener class:
class ShakeEventListener implements SensorEventListener {
@Override
public void onSensorChanged(SensorEvent event) {
handleShake(event); // see below
}
}
C. Boot receiver implementation - register a shake listener for TYPE_ACCELEROMETER events
public class OnBootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent){
SensorManager sManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
sensor = sManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sManager.registerListener(new ShakeEventListener(), sensor, SensorManager.SENSOR_DELAY_NORMAL); // or other delay
}
}
D. If Shake motion is detected - start your main activity:
void handleShake(event) {
if (shake movement detected) {
// start main activity
Intent intent = new Intent(getBaseContext(), myActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
The only thing we left out is the "shake movement detected" logic.
Here you can find a reasonably good base implementation.
Use function onSensorChanged(). You will probably need to variate on it
until you get it right.
Permissions:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>