光线传感器&指南针

使用传感器需要用系统服务。传感器管理器。光线传感器

public class MainActivity extends Activity {
	public static final String TAG = "MainActivity";
	private SensorManager sm;
	private myListener listener;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		sm = (SensorManager) getSystemService(SENSOR_SERVICE);
		// 光线传感器
		Sensor sensor = sm.getDefaultSensor(Sensor.TYPE_LIGHT);
		listener = new myListener();
		// rate是采样频率
		sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI);
	}

	private class myListener implements SensorEventListener {

		@Override
		public void onSensorChanged(SensorEvent event) {
			float light = event.values[0];
			Log.i(TAG, "光线强度:" + light);
		}

		@Override
		public void onAccuracyChanged(Sensor sensor, int accuracy) {

		}

	}

	@Override
	protected void onDestroy() {

		sm.unregisterListener(listener);
		listener = null;
		super.onDestroy();
	}

}

方向传感器指南针

public class MainActivity extends Activity {
	public static final String TAG = "MainActivity";
	private SensorManager sm;
	private myListener listener;
	private ImageView iv;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		iv = (ImageView) findViewById(R.id.iv);

		sm = (SensorManager) getSystemService(SENSOR_SERVICE);
		// 光线传感器
		Sensor sensor = sm.getDefaultSensor(Sensor.TYPE_ORIENTATION);
		listener = new myListener();
		// rate是采样频率
		sm.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_GAME);
	}

	private class myListener implements SensorEventListener {

		float start = 0;

		@Override
		public void onSensorChanged(SensorEvent event) {
			// 0=North,90=East,180=South,270=West
			float angle = event.values[0];// 手机与正北方向的夹角
			RotateAnimation ra = new RotateAnimation(start, -angle,
					Animation.RELATIVE_TO_SELF, 0.5f,
					Animation.RELATIVE_TO_SELF, 0.5f);
			iv.startAnimation(ra);
			start = angle;
		}

		@Override
		public void onAccuracyChanged(Sensor sensor, int accuracy) {

		}

	}

	@Override
	protected void onDestroy() {

		sm.unregisterListener(listener);
		listener = null;
		super.onDestroy();
	}

}




你可能感兴趣的:(光线传感器&指南针)