+5

Tìm hiểu về Sensor trong android

Một trong những khác biệt khi phát triển các ứng dụng giữa pc và mobile mà chúng ta có thể dễ dàng nhận thấy đó là mobile có cung cấp cho chúng ta các loại cảm biến. Việc sử dụng cảm biến này có thể tạo ra những ứng dụng hữu ích và thực tế đã có rất nhiều các nhà phát triển thêm nó vào trong các ứng dụng của mình. Hôm nay mình viết bài viết này để cùng với các bạn tìm hiểu về cảm biến trong android.

Các loại cảm biến trong android

Android có hỗ trợ cho chúng ta 3 loại cảm biến:

  1. Cảm biến gia tốc: Cho biết về lực gia tốc và độ quay của thiết bị theo các trục tọa độ
  2. Cảm biến vị trí: Cho biết về vị trí vật lý của thiết bị
  3. Cảm biến môi trường: Cho biết thông tin về nhiệt độ, độ ẩm ... của môi trường.

Android Sensor Framework

Chúng ta đã biết về các loại cảm biến trong android vậy để truy cập vào các cảm biến có sẵn trong thiết bị thì android có cung cấp cho chúng ta Android Sensor Framework. Với Android Sensor Framework chúng ta có thể sử dụng nó để kiểm tra liệu thiết bị có hỗ trợ cảm biến mà chúng ta cần truy cập hay không, lấy dữ liệu sensor, đăng kí hay hủy đăng kí lắng nghe sự kiện cảm biến thay đổi... Vậy để truy cập sensor trong ứng dụng android và lấy dữ liệu cần thiết thì chúng ta cần phải làm những thao tác nào?

SensorManager và Sensor: Hai lớp này cung cấp cho chúng ta các phương thức để có thể truy cập và lấy dữ liệu từ các sensor

Bạn có thể tạo một đối tượng SensorManager qua phưong thức getSystemService(SENSOR_SERVICE) Lớp Sensor có định nghĩa cho chúng ta một số hằng số truy cập vào các loại cảm biến khác nhau:

  • Sensor.TYPE_GYROSCOPE

  • Sensor.TYPE_MAGNETIC_FIELD

  • Sensor.TYPE_ORIENTATION

  • Sensor.TYPE_ACCELEROMETER

Có thể truy cập cảm biến qua hàm sensorManager.getDefaultSensor()

Sensor listener: Khi muốn yêu cầu một loại cảm biến nào bạn cần đăng kí một Sensor listener để nó có thể thông báo cho bạn khi dữ liệu của sensor thay đổi. Một số lưu ý với Sensor listener đó là:

  • Bạn nên đăng kí Sensor listener trong hàm onResume() và hủy đăng kí trong hàm onPause() để tránh việc sử dụng không cần thiết và tiêt kiệm pin cho thiết bị
  • onSensorChanged() được gọi khi dữ liệu cảm biến thay đổi và nó có thể được gọi rất nhiều lần chính vì điều này chúng ta nên hạn chế sử lý logic nhiều trong hàm này.

Bây giờ chung ta sẽ implement thử một project nhỏ hiện thị một compass dựa vào cảm biến Chúng ta cần tạo một custom view để hiển thị compass và một Activity quản lý việc đăng kí và hủy đăng kí Sensor listener Tạo view compass:

public class MyCompassView extends View {

        private Paint paint;
        private float position = 0;

        public MyCompassView(Context context) {
                super(context);
                init();
        }

        private void init() {
                paint = new Paint();
                paint.setAntiAlias(true);
                paint.setStrokeWidth(2);
                paint.setTextSize(25);
                paint.setStyle(Paint.Style.STROKE);
                paint.setColor(Color.WHITE);
        }

        @Override
        protected void onDraw(Canvas canvas) {
                int xPoint = getMeasuredWidth() / 2;
                int yPoint = getMeasuredHeight() / 2;

                float radius = (float) (Math.max(xPoint, yPoint) * 0.6);
                canvas.drawCircle(xPoint, yPoint, radius, paint);
                canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), paint);
                canvas.drawLine(
                                xPoint,
                                yPoint,
                                (float) (xPoint + radius
                                                * Math.sin((double) (-position) / 180 * 3.143)),
                                (float) (yPoint - radius
                                                * Math.cos((double) (-position) / 180 * 3.143)), paint);

                canvas.drawText(String.valueOf(position), xPoint, yPoint, paint);
        }

        public void updateData(float position) {
                this.position = position;
                invalidate();
        }
}

Tạo Activity đăng kí truy cập cảm biến gia tốc và hiển thị compass:

public class MainActivity extends Activity {

        private static SensorManager sensorService;
        private MyCompassView compassView;
        private Sensor sensor;

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                compassView = new MyCompassView(this);
                setContentView(compassView);

                sensorService = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
                sensor = sensorService.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        }
        
         @Override
         protected void onResume() {
                super.onResume();
                if (sensor != null) {
                        sensorService.registerListener(mySensorEventListener, sensor,
                                        SensorManager.SENSOR_DELAY_NORMAL);
                        Log.i("Compass MainActivity", "Registerered for ORIENTATION Sensor");
                } else {
                        Log.e("Compass MainActivity", "Registerered for ORIENTATION Sensor");
                        Toast.makeText(this, "ORIENTATION Sensor not found",
                                        Toast.LENGTH_LONG).show();
                        finish();
                }
        }

        @Override
        protected void onPause() {
            super.onPause();
            if (sensor != null) {
                  sensorService.unregisterListener(mySensorEventListener);
            }
        }

        private SensorEventListener mySensorEventListener = new SensorEventListener() {

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

                @Override
                public void onSensorChanged(SensorEvent event) {
                        // angle between the magnetic north direction
                        // 0=North, 90=East, 180=South, 270=West
                        float azimuth = event.values[0];
                        compassView.updateData(azimuth);
                }
        };
}

Tham khảo: https://developer.android.com/guide/topics/sensors/sensors_overview.html


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí