Android Sensor App _ Compass (first line Code tutorial)

Source: Internet
Author: User

1. Detect which sensors are in your phone

Checksensor.java Code Schema

1, the use of a ScrollView package TextView all the sensor manufacturers, equipment name, version, type number, etc. to print out

2, in order to get the sensor name, using a static inner class, the function of this static inner class is to convert (int) Sensor.gettype () into the corresponding sensor name

The only method of this inner class, getsensortypename (int type), is to play this role

Package com.example.checksensor;

Import java.util.List;

Import Android.content.Context;
Import Android.hardware.Sensor;
Import Android.hardware.SensorManager;
Import Android.os.Bundle;
Import android.support.v7.app.ActionBarActivity;
Import Android.util.Log;
Import Android.widget.TextView;


public class Mainactivity extends Actionbaractivity {

@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
TextView textviewofshowsensorlist = (TextView) Findviewbyid (r.id.show_sensor);
Sensormanager Sensormanager = (sensormanager) getsystemservice (Context.sensor_service);
list<sensor> sensorlist = sensormanager.getsensorlist (Sensor.type_all);
StringBuilder sb = new StringBuilder ();
Sb.append ("The phone has a total of sensors:" +sensorlist.size () + "\ n");
String typeName = "";
for (Sensor i:sensorlist) {
LOG.D ("", String.Format ("type number:%d\n", I.gettype ()));
}
for (Sensor i:sensorlist) {
TypeName = Sensortypename.getsensortypename (I.gettype ());
Sb.append (String.Format ("Sensor name:%s\n", typeName));
Sb.append (String.Format ("Device Name:%s\n", I.getname ()));
Sb.append (String.Format ("Device version:%s\n", I.getversion ()));
Sb.append (String.Format ("Equipment Supplier:%s\n\n", I.getvendor ()));
}
Textviewofshowsensorlist.settext (Sb.tostring ());
}
Why subclasses can be described as static types,
The advantage of creating a new class to store various sensor types is that each time you create a new class, you don't have to spend a lot of money
To store these insignificant things.
Static Class Sensortypename {
static private String []typename;
Why the use of keywords in static, it should have been static AH
static {
TypeName = new STRING[20];
Typename[sensor.type_gravity] = "Gravity sensor";
Typename[sensor.type_light] = "light sensor";
Typename[sensor.type_pressure] = "pressure sensor";
Typename[sensor.type_relative_humidity] = "type_relative_humidity";
Typename[sensor.type_ambient_temperature] = "Type_ambient_temperature";
Typename[sensor.type_gyroscope] = "gyroscope";
Typename[0] = "Unknown";
Typename[sensor.type_accelerometer] = "acceleration";
Typename[sensor.type_magnetic_field] = "magnetism";
Typename[sensor.type_orientation] = "direction";
Typename[sensor.type_temperature] = "Temperature";
Typename[sensor.type_proximity] = "proximity, distance sensor";
Typename[sensor.type_linear_acceleration] = "linear acceleration";
Typename[sensor.type_rotation_vector] = "rotation vector";
Itsnames[sensor.type_game_rotation_vector] = "Type_game_rotation_vector";
TYPENAME[14] = "type_magnetic_field_uncalibrated";
}
public static String getsensortypename (int type) {
if (Type > 0 && type < typename.length) {
return Typename[type];
}
return null;
}
}
}

XML file:

<scrollview
Android:layout_width= "Match_parent"
android:layout_height= "Match_parent"
Xmlns:android= "Http://schemas.android.com/apk/res/android" >
<linearlayout
Android:layout_width= "Match_parent"
android:layout_height= "Wrap_content" >

<textview android:id= "@+id/show_sensor"
Android:layout_width= "Match_parent"
android:layout_height= "Match_parent" >
</TextView>

</LinearLayout>
</ScrollView>

The results were as follows:

2. Create a new Compass instance

Studycompass.java Architecture

Create a new Sensormanager class and Magneticsensor, Accelerometersensor.

By using Sensormanager.registerlistener (Listener, Magneticsensor, sensormanager.sensor_delay_normal);

Creates a new Sensoreventlistener object listener. Rewrite the onsensorchanged (sensorevent sensorevent).

Note the point:

You need to use Clone () when using animation effects. Otherwise, it will point to the same reference.

Rotateanimation.setfillafter (TRUE);
Compassimg.startanimation (rotateanimation);

Package com.example.studycompass;

Import android.app.Activity;
Import Android.content.Context;
Import Android.hardware.Sensor;
Import android.hardware.SensorEvent;
Import Android.hardware.SensorEventListener;
Import Android.hardware.SensorManager;
Import Android.os.Bundle;
Import android.view.animation.Animation;
Import android.view.animation.RotateAnimation;
Import Android.widget.ImageView;


public class Mainactivity extends Activity {

Private ImageView compassimg;
Private ImageView arrowimg;
Private Sensormanager Sensormanager;
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Compassimg = (ImageView) Findviewbyid (r.id.compass_img);
Arrowimg = (ImageView) Findviewbyid (r.id.arrow_img);
Sensormanager = (Sensormanager) getsystemservice (Context.sensor_service);
Sensor Magneticsensor = (sensor) sensormanager.getdefaultsensor (Sensor.type_magnetic_field);
Sensor Accelerometersensor = (sensor) sensormanager.getdefaultsensor (sensor.type_accelerometer);
Sensormanager.registerlistener (Listener, Magneticsensor, sensormanager.sensor_delay_normal);
Sensormanager.registerlistener (Listener, Accelerometersensor, sensormanager.sensor_delay_normal);
}
protected void OnDestroy () {
Super.ondestroy ();
if (Sensormanager! = null) {
Sensormanager.unregisterlistener (listener);
}
}
Private Sensoreventlistener listener = new Sensoreventlistener () {
float[] Magneticarray = new Float[3];
float[] Accelerometerarray = new Float[3];
private float Lastrotatedegree;
private float Rotatedegree;
@Override
public void onsensorchanged (Sensorevent sensorevent) {
TODO auto-generated Method Stub
if (sensorEvent.sensor.getType () = = Sensor.type_magnetic_field) {
/**
* The Clone method must be used here, otherwise, it will point to the same reference
*/
Magneticarray = SensorEvent.values.clone ();
} else if (sensorEvent.sensor.getType () = = Sensor.type_accelerometer) {
Accelerometerarray = SensorEvent.values.clone ();
}

float[] rotation = new FLOAT[9];
float[] Orientation = new FLOAT[3];
Sensormanager.getrotationmatrix (rotation, NULL, Accelerometerarray, Magneticarray);
Sensormanager.getorientation (rotation, orientation);
Rotatedegree =-(float) math.todegrees (orientation[0]);
if (Math.Abs (Lastrotatedegree-rotatedegree) > 1) {
Rotateanimation rotateanimation = new Rotateanimation (Lastrotatedegree, Rotatedegree, Animation.relative_to_self, 0.5f, Animation.relative_to_self, 0.5f);
Keep the animation in the end result
Rotateanimation.setfillafter (TRUE);
Compassimg.startanimation (rotateanimation);
Lastrotatedegree = Rotatedegree;
}
}

@Override
public void onaccuracychanged (Sensor paramsensor, int paramint) {
TODO auto-generated Method Stub

}

};
}

First use the superimposed two pictures, one as the pointer, the other as the background four directions L

XML file:

<relativelayout xmlns:android= "Http://schemas.android.com/apk/res/android"
Android:layout_width= "Match_parent"
android:layout_height= "Match_parent" >

<imageview
Android:id= "@+id/compass_img"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
Android:layout_centerinparent= "true"
android:src= "@drawable/compass"/>

<imageview
Android:id= "@+id/arrow_img"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
Android:layout_centerinparent= "true"
android:src= "@drawable/arrow"/>

</RelativeLayout>

Get results:

Android Sensor App _ Compass (first line Code tutorial)

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.