(Android practice) implements the shake Function

Source: Internet
Author: User

// Sensor Manager
Private SensorManager mSensorManager;

// Vibrator
Private Vibrator vibrator;

// Activity Manager
ActivityManager activityManager;


// 1 obtain hardware information
MSensorManager = (SensorManager) getSystemService (SENSOR _

SERVICE );
Vibrator = (Vibrator) getSystemService (Service. VIBRATOR_SERVICE );
ActivityManager = (ActivityManager) getSystemService (ACTIVITY_SERVICE );

// 2 check whether the current mobile phone has an acceleration sensor. If no acceleration sensor is provided, the service is terminated directly and the service is not started.
List <Sensor> sensors = mSensorManager. getSensorList (Sensor. TYPE_ACCELEROMETER );
If (sensors! = Null)
If (sensors. size () = 0)
Return;

// 3 generate a listening event
SensorEventListener sensorelistener = new SensorEventListener (){
@ Override
Public void onAccuracyChanged (Sensor sensor, int accuracy ){
// TODO Auto-generated method stub

}
// Sensor changes
@ Override
Public void onSensorChanged (SensorEvent event ){
// TODO Auto-generated method stub
Int sensorType = event. sensor. getType ();

// Read the shake sensitive Value
Int shakeSenseValue = Integer. parseInt (getResources (). getString (R. string. shakeSenseValue ));;
// Values [0]: X axis, values [1]: Y axis, values [2]: Z axis
Float [] values = event. values;

If (sensorType = Sensor. TYPE_ACCELEROMETER ){
If (Math. abs (values [0])> shakeSenseValue | Math. abs (values [1])> shakeSenseValue | Math. abs (values [2])> shakeSenseValue )){
// Trigger the event and execute the open application action
Vibrator. vibrate (500 );
}
}
}

};

// 4 register a listening event
MSensorManager. registerListener (sensorelistener,
MSensorManager. getdefasensensor (Sensor. TYPE_ACCELEROMETER ),
SensorManager. SENSOR_DELAY_NORMAL );

}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.