本文主要是介绍Android重力感应SensorEventListener详解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
两个类:
1、SensorTest类,是Acvitivity
2、SensorListenerTest类,实现了SensorEventListener类,
SensorTest.java:
package com.sensor;import android.app.Activity;
import android.os.Bundle;public class SensorTest extends Activity {/** Called when the activity is first created. */SensorListenerTest sensorListenerTest;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);// 传参数的时候,用this,不是自己新建的ContextsensorListenerTest = new SensorListenerTest(this);}// 添加OnResume和OnStop,注册和取消Sensor服务。@Overrideprotected void onResume() {// 监听服务,在activity和Listener里面都要注册,这是一个难点。不要只在一个地方注册。// TODO Auto-generated method stubsuper.onResume();sensorListenerTest.enableSensor();}@Overrideprotected void onStop() {// TODO Auto-generated method stubsuper.onStop();sensorListenerTest.disableSensor();}}
SensorListenerTest.java:
package com.sensor;import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.util.Log;public class SensorListenerTest implements SensorEventListener {private SensorManager mSensorManager;private Sensor sensor;private float mLastX, mLastY, mLastZ;private Context mContext;public SensorListenerTest(Context context) {mContext = context;// 在构造函数里面注册Sensor服务enableSensor();}// 注册传感器服务,在本java和Activity里面都要注册,但是取消注册的时候,只在activity里面取消注册即可。public void enableSensor() {// 在这里真正注册Service服务mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE);sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);if (mSensorManager ==
这篇关于Android重力感应SensorEventListener详解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!