Android傳感器數據獲取的方法

本文實例為大傢分享瞭Android傳感器數據獲取的具體代碼,供大傢參考,具體內容如下

接著上篇wifi列表獲取,我們這篇接著說傳感器。還是看代碼

我們先自己定義一個傳感器的工具類(因為我這邊隻是獲取瞭部分的傳感器,需要獲取額外的傳感器自己配置一下就行瞭,工具類通過重載提供瞭不同的構造方法):

public class SensorUtils implements SensorEventListener {
 
    private SensorManager manager;
 
    /**
     * @param context 多個傳感器
     * @param sensorList
     */
    public void RegisterSensor(Context context, List<Sensor> sensorList){
        manager = (SensorManager) context.getSystemService(SENSOR_SERVICE);
        for(Sensor sensors : sensorList){
            manager.registerListener(this,sensors,SensorManager.SENSOR_DELAY_NORMAL);
        }
    }
 
    /**
     * @param context 單個傳感器
     * @param sensor
     */
    public void RegisterSensor(Context context, Sensor sensor){
        manager = (SensorManager) context.getSystemService(SENSOR_SERVICE);
        manager.registerListener(this,sensor,SensorManager.SENSOR_DELAY_NORMAL);
    }
 
    @Override
    public void onSensorChanged(SensorEvent event) {
        switch (event.sensor.getType()){
            case Sensor.TYPE_ACCELEROMETER:
                //給加速度傳感器設置回調監聽
                sensorCallBack.acceleratedCallBack(event);
                break;
            case Sensor.TYPE_GYROSCOPE:
                //給陀螺儀傳感器設置回調監聽
                sensorCallBack.gyroscopeCallBack(event);
                break;
            case Sensor.TYPE_MAGNETIC_FIELD:
                //給磁場傳感器設置回調監聽
                sensorCallBack.magneticFieldCallBack(event);
                break;
            case Sensor.TYPE_PRESSURE:
                //給氣壓計傳感器設置回調監聽
                sensorCallBack.pressureCallBack(event);
                break;
        }
 
    }
 
    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
 
    }
 
    //使用完之後記得取消註冊
    public void UnRegisterSensor(){
        if (manager != null){
            manager.unregisterListener(this);
        }
    }
 
    public interface SensorCallBack{
        void acceleratedCallBack(SensorEvent event);
 
        void gyroscopeCallBack(SensorEvent event);
 
        void magneticFieldCallBack(SensorEvent event);
 
        void pressureCallBack(SensorEvent event);
    }
 
   private SensorCallBack sensorCallBack;
 
    public SensorUtils(SensorCallBack sensorCallBack){
        this.sensorCallBack = sensorCallBack;
    }
 
}

然後我們在activity中去使用工具類:

//初始化
sensorUtils = new SensorUtils(this);
sensorUtils.RegisterSensor(this, sensorList);

activity中別忘瞭實現SensorUtil中的回調監聽

public class SensorActivity extends BaseActivity<BaseViewModel, ActivitySensorBinding> implements SensorUtils.SensorCallBack{
 
  //do something
}

然後在自己設置的回調監聽中去實現自己想要的功能

@Override
    public void acceleratedCallBack(SensorEvent event) {
        //可以做自己想要的操作
        if (event != null) {
            float[] values = event.values;
            float x1 = values[0];
            float y1 = values[1];
            float z1 = values[2];
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(getString(R.string.accelerometer_number)).append("\n");
            stringBuffer.append(getString(R.string.x1)).append(x1).append("\n");
            stringBuffer.append(getString(R.string.y1)).append(y1).append("\n");
            stringBuffer.append(getString(R.string.z1)).append(z1);
            if (!viewDateBinding.scrollView.isMove()) {
                handler.post(() -> viewDateBinding.tvAccelerated.setText(stringBuffer.toString()));
            }
            if (flagAccelerated) {
                DataBassManager.getInstance(SensorActivity.this).insertSensor(new TableBean(null,stringBuffer.toString(),null,null,null));
            }
            flagAccelerated = false;
        }
    }
 
    @Override
    public void gyroscopeCallBack(SensorEvent event) {
        //可以做自己想要的操作
        if (event != null) {
            float x2 = event.values[0];
            float y2 = event.values[1];
            float z2 = event.values[2];
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(getString(R.string.gyroscope_number)).append("\n");
            stringBuffer.append(getString(R.string.x2)).append(x2).append("\n");
            stringBuffer.append(getString(R.string.y2)).append(y2).append("\n");
            stringBuffer.append(getString(R.string.z2)).append(z2);
            if (!viewDateBinding.scrollView.isMove()) {
                handler.post(() -> viewDateBinding.tvGyroscope.setText(stringBuffer.toString()));
            }
            if (flagGyroscope) {
                DataBassManager.getInstance(SensorActivity.this).insertSensor(new TableBean(null,null,stringBuffer.toString(),null,null));
            }
            flagGyroscope = false;
        }
    }
 
    @SuppressLint("DefaultLocale")
    @Override
    public void magneticFieldCallBack(SensorEvent event) {
        //可以做自己想要的操作
        if (event != null) {
            float x3 = event.values[0];
            float y3 = event.values[1];
            float z3 = event.values[2];
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(getString(R.string.magnetic_field_number)).append("\n");
            stringBuffer.append(getString(R.string.x3)).append(String.format("%.2f", x3)).append("\n");
            stringBuffer.append(getString(R.string.y3)).append(String.format("%.2f", y3)).append("\n");
            stringBuffer.append(getString(R.string.z3)).append(String.format("%.2f", z3));
            if (!viewDateBinding.scrollView.isMove()) {
                handler.post(() -> viewDateBinding.tvMagneticField.setText(stringBuffer.toString()));
            }
            if (flagMagneticField) {
                DataBassManager.getInstance(SensorActivity.this).insertSensor(new TableBean(null,null,null,stringBuffer.toString(),null));
            }
            flagMagneticField = false;
        }
    }
 
    @Override
    public void pressureCallBack(SensorEvent event) {
        //可以做自己想要的操作
        if (event != null) {
            float x4 = event.values[0];
            String str4 = getString(R.string.pressure_number) + x4;
            if (!viewDateBinding.scrollView.isMove()) {
                handler.post(() -> viewDateBinding.tvPressure.setText(str4));
            }
            if (flagPressure) {
                DataBassManager.getInstance(SensorActivity.this).insertSensor(new TableBean(null,null,null,null,str4));
            }
            flagPressure = false;
        }
    }

我這邊是將數據通過按鈕的點擊事件存儲進瞭數據庫,註意傳感器的回調是實時的,所以如果想要獲取某一時刻,需要自己通過boolean去判斷是否需要獲取回調數據

最後,記得取消監聽,因為我是在activity中去註冊的,所以取消註冊也是在activity中去做:

protected void onStop() {
        super.onStop();
        sensorUtils.UnRegisterSensor();
    }

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: