When it comes to shaking, you may think of the shake function of WeChat. Later, many APPs also followed the Shake-related functions. Here we will introduce how to shake.
Step 1:Declare a SensorManager object
Step 2:Rewrite the onResume method of the Activity, register the sensor listening event in the method, and specify the sensor type to be listened to.
Step 3:Rewrite the onPause method of the Activity, in which the sensor event is logged out
Step 4:Write a sensor event listener, which inherits from the SensorEventListener, and requires both onSensorChanged and onAccuracyChanged methods. Among them, the previous method is triggered when sensing the information changes, and the business logic is processed here; the latter method is triggered when the longitude changes, and generally does not need to be processed.
Code Example
Add permissions
<uses-permission android:name=""/>
public class MainActivity extends BaseActivity implements SensorEventListener { private TextView tv_sensor; private SensorManager mSensorMgr;//Declare a sensor manager object private Vibrator mVibrator;//Declare a vibrator object @Override protected MvcBaseModel getModelImp() { return null; } @Override protected int getContentLayoutId() { return .activity_main; } @Override protected void initWidget() { tv_sensor = findViewById(.tv_sensor); //Get sensor manager object from system service mSensorMgr = (SensorManager) getSystemService(Context.SENSOR_SERVICE); //Get vibrator object from system service mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); } @Override protected void onPause() { (); (this); } @Override protected void onResume() { (); (this ,(Sensor.TYPE_ACCELEROMETER) ,SensorManager.SENSOR_DELAY_NORMAL); } @Override public void onSensorChanged(SensorEvent event) { if (() == Sensor.TYPE_ACCELEROMETER){// Acceleration change event //value[0]: X-axis, value[1]: Y-axis, values[2]: Z-axis float[] values = ; if (((values[0])>15) || (values[1])>15 || (values[2])>15){ tv_sensor.setText("Congratulations on shaking"+()); //After the system detects a shake event, the vibrating phone prompts the user to be prompted by the user (500); } } } //Calling back to this method when the sensor accuracy changes, generally no processing is required @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }
In actual use, I found that the system will have multiple callbacks after shaking. Here we can add locks after a response and no longer responds. Continue to respond after three seconds. This can achieve the purpose of performing relevant operations only once.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.