Android sensor (3) Acceleration

Source: Internet
Author: User

Taking nesus s as an example, from USB to the receiver is the Y axis, adjust the volume to the switch screen is the X axis, and the on-screen direction is the Z axis.

Public class accesssensormanageractivity extends activity {

@ Override
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. Main );

Sensormanager = (sensormanager) getsystemservice (context. sensor_service );
Sensor sensor = sensormanager. getdefasensensor (sensor. type_accelerometer );
Sensormanager. registerlistener (New accelistener (), sensor, sensormanager. sensor_delay_normal );
}
}

Class accelistener implements sensoreventlistener {
Private float gravity [] = new float [3];
Private float linear_acceleration [] = new float [3];
@ Override
Public void onsensorchanged (sensorevent event ){
// Todo auto-generated method stub

Final float alpha = 0.8f;

 

// Calculate the acceleration in the direction of X, Y, and Z respectively.

Gravity [0] = Alpha * gravity [0] + (1-alpha) * event. Values [0];
Gravity [1] = Alpha * gravity [1] + (1-alpha) * event. Values [1];
Gravity [2] = Alpha * gravity [2] + (1-alpha) * event. Values [2];

// Obtain the acceleration in all directions of X, Y, and Z, and remove the influence of gravity acceleration.
Linear_acceleration [0] = event. Values [0]-gravity [0];
Linear_acceleration [1] = event. Values [1]-gravity [1];
Linear_acceleration [2] = event. Values [2]-gravity [2];


System. Out. println ("X:" + linear_acceleration [0]);
System. Out. println ("Y:" + linear_acceleration [1]);
System. Out. println ("Z:" + linear_acceleration [2]);
}

@ Override
Public void onaccuracychanged (sensor, int accuracy ){
// Todo auto-generated method stub

}

}

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.