Android Accelerometer Magical and custom view

Source: Internet
Author: User
Tags acos

The example in this section is a tilt angle measurement application that accurately measures the tilt angle of your phone and the horizontal plane, using the acceleration sensor inside the Android sensor. The physical meaning represented by the various values of the accelerometer, coupled with a very simple algorithm, can be used to measure the tilt angle.

The angle value is displayed exactly as the phone tilts and the effect

Not much nonsense to say directly on the code, there is a clear explanation

 PackageSina. Creamazing.angle_view;Importandroid.app.Activity;ImportAndroid.content.Context;Importandroid.graphics.BitmapFactory;ImportAndroid.graphics.Canvas;ImportAndroid.graphics.Color;ImportAndroid.graphics.Paint;ImportAndroid.hardware.Sensor;Importandroid.hardware.SensorEvent;ImportAndroid.hardware.SensorEventListener;ImportAndroid.hardware.SensorManager;ImportAndroid.os.Bundle;ImportAndroid.util.DisplayMetrics;ImportAndroid.util.Log;ImportAndroid.view.View; Public classAngleviewactivityextendsActivity {/**Called when the activity is first created.*/    //declare a Sensormanager management sensor, a custom class MyView, to draw the image you want in MyView    PrivateSensormanager Sensormanager; PrivateMyView MyView; @Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); //Instantiate SensormanagerSensormanager = (Sensormanager) This. Getsystemservice (Sensor_service); //Displaymetrics is used to get the screen size, and then pass it to the MyView to easily draw the graphical interface;Displaymetrics display =NewDisplaymetrics ();        Getwindowmanager (). Getdefaultdisplay (). Getmetrics (display); //constructs a myview,display.widthpixels is the width of the current screen, Display.heightpixels is the height of the current screenMyView =NewMyView ( This, Display.widthpixels, display.heightpixels); //This is not the layout file in the Layouts folder, directly is our myview. Setcontentview (MyView); }    //registering and unblocking listeners in Onresume (), OnPause ()@Overrideprotected voidOnresume () {Super. Onresume ();                Sensormanager.registerlistener (MyView, Sensormanager.getdefaultsensor (Sensor.type_accelerometer),    Sensormanager.sensor_delay_normal); } @Overrideprotected voidOnPause () {Sensormanager.unregisterlistener (MyView); LOG.I ("Unregister", "OK"); Super. OnStop (); }}//the custom class MyView realizes Sensoreventlistener because the sensor is to be sensed. classMyViewextendsViewImplementsSensoreventlistener {//float x = 0; //float y = 0; //the value on the z-axis is what we need, and the z-axis is perpendicular to the horizontal plane, and when you place the phone horizontally it's a value of 10, which is 0 when you place it vertically.    floatz = 0; Private floatwidth; Private floatheight;        Paint p;  PublicMyView (Context context) {Super(context); //TODO auto-generated Constructor stub    }     PublicMyView (Context context,floatWidthfloatheight) {        Super(context);  This. width =width;  This. Height =height; //get a brush, set basic propertiesp =NewPaint ();    P.setstyle (Paint.Style.STROKE); }//In the OnDraw () method is what we really want to draw, that is, the image that really appears on the screen.@Overrideprotected voidOnDraw (canvas canvas) {//first draw a picture of the background, the picture is a good pre-PS a background map.         Canvas is the meaning of the canvas, we need to use the brush p to draw on canvas canvases. Canvas.drawbitmap (Bitmapfactory.decoderesource (Getresources (), r.drawable.circle), 0, 0, p); //Draw the background to draw text, and then set the brush. P.settextsize (50); //The text you draw is the actual measured angle, before which the z-value conversion is the Todegree () method. Canvas.drawtext (Todegree (z) + "°", WIDTH/2-HEIGHT/2, p); //after drawing a circle, the circle becomes larger and smaller as the angle changes. P.setcolor (color.red); P.setstrokewidth (2); Canvas.drawcircle (Width/2, HEIGHT/2, 20 *z, p); }//How to convert the current acceleration value into the current angle value? This requires a certain hardware basis to understand the principle, do not know that students can see some of the acceleration sensor aspects of the book, about the speed of//sensors also have many applications, such as speed measurement, displacement measurement, which requires a more complex algorithm, which is no longer introduced    PrivateString Todegree (floatZZ) {        //The first step is to determine if the value of the acceleration is greater than 10, less than 10, because acceleration is not stable during the motion, and we are going to measure the steady value in the stationary state.         if(ZZ > 10) {ZZ= 10; } Else if(ZZ <-10) {ZZ=-10; }        //ACOs (ZZ/10) is able to calculate the radian value of the tilt angle.         DoubleR = Math.acos (ZZ/10); //then convert the Radian value to the angle value        intdegree = (int) (R * 180/Math.PI); //finally returns a string        returnstring.valueof (degree); } @Override Public voidonsensorchanged (Sensorevent event) {//TODO auto-generated Method Stub//x = event.values[0]; //y = event.values[1];                if(Event.sensor.getType () = =sensor.type_accelerometer) {            //get the acceleration value of the z-axisz = event.values[2]; }                //call this method to redrawinvalidate (); } @Override Public voidOnaccuracychanged (sensor sensor,intaccuracy) {        //TODO auto-generated Method Stub    }}

Project Source:

Http://115.com/file/an9mk3ya#AngleView.rar

Android Accelerometer Magical and custom view

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.