How to create an android app that activates on sha

2019-03-13 18:03发布

问题:

I want to create an app that **starts the Main activity whenever the device shakes, even when screen locked. Can anyone explain how to do that?

I have an idea that it requires to create a service that runs in background, but I am struggling with actual coding and don't know how to do it.

回答1:

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>