Android重力传感器代码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
所建立Android项目包的名称可自定义修改
//=============syx==============//
package com.example.yidong;
//==============================//
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.Menu;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
public class MainActivity extends Activity implements SensorEventListener {
SensorManager sensorManager;
EditText editText;
EditText editText1;
EditText editText2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(yout.activity_main);
editText=(EditText)findViewById(R.id.editText1);
editText1=(EditText)findViewById(R.id.editText2);
editText2=(EditText)findViewById(R.id.editText3);
//获取重力传感器服务
sensorManager=(SensorManager)getSystemService(MainActivity.this.SENSOR_SERVICE);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
//注册加速度传感器监听器
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
sensorManager.unregisterListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) { // TODO Auto-generated method stub
}
//当参数值改变时调用此函数
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
float[] values=event.values;
StringBuilder sb=new StringBuilder();
StringBuilder sb1=new StringBuilder();
StringBuilder sb2=new StringBuilder();
sb.append("X的加速度=");
sb.append(values[0]+"\n");
sb1.append("Y的加速度=");
sb1.append(values[1]+"\n");
sb2.append("z的加速度=");
sb2.append(values[2]+"\n");