Package com.kane.sensortest;
Import Java.util.Random;
Import Android.hardware.Sensor;
Import android.hardware.SensorEvent;
Import Android.hardware.SensorEventListener;
Import Android.hardware.SensorManager;
Import Android.os.Bundle;
Import android.app.Activity;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
Import Android.widget.TextView;
Import Android.widget.Toast; public class Mainactivity extends activity {private TextView content; private Button btn;//Lottery private string[] Allresult
S={"She Loves Me", "She Doesn't Love Me", "She Loves him"};
Private Random random=new Random ();
Private Boolean flag=false;
Private Long starttime =-1;
x acceleration of the initial horizontal direction private float max = 0;
private float min = 0; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (
R.layout.activity_main);
Content= (TextView) Findviewbyid (r.id.content);
Btn= (Button) Findviewbyid (R.ID.BTN); Call Sensor Service SensorManager manager= (Sensormanager) Getsystemservice (Sensor_service); Set up the Sensor object Sensor s=manager.getdefaultsensor (sensor.type_accelerometer)//Accelerator object, there are many other objects//settings listening, when the value in the sensor changes, Automatic Listener Feedback Manager.registerlistener (new Sensoreventlistener () {@Override public void onsensorchanged (Sensorevent event {if (flag) {if (starttime==-1) {Starttime=system.currenttimemillis ()}////when there is a change, this method is automatically executed//the acceleration value in three directions can be obtained by the event float[
] Values=event.values;
/*stringbuilder builder=new StringBuilder ();
Builder.append (values[0]+ "\ r \ n");
Builder.append (values[1]+ "\ r \ n");
Builder.append (values[2]+ "\ r \ n"); Content.settext (builder); */if (Values[0]>max) {max=values[0];} if (values[0]<min) {min=values[0]; if (Max > 1 0 && min < -10) {flag = false; Long X=system.currenttimemillis (); if (x-starttime>2000) {Toast.mak
EText (Mainactivity.this, "timeout, please shake Again", Toast.length_short). Show ();
else {//can produce the result//randomly generated int index=random.nextint (3); Content.settext ("Result:" +allresults[index]);
} starttime =-1;
@Override public void onaccuracychanged (Sensor Sensor, int accuracy) {}}, S, 0); Btn.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {flag=true; Content.settext ("Please open
Start shaking ");
}
}); }
}
See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/OS/extra/