光照强度

时间:2018-01-23 12:02:20

标签: java android

以下服务检测光强度,并在每个传感器更改事件的文件中写入其值。我想要的是,每当调用此服务时,它应该在那时写入传感器的值。不是传感器的改变。

我的代码如下:

public class LightIntensity extends Service {

    private SensorManager mSensorManager;
    private SensorEventListener mEventListenerLight;
    private float lastLightValue;
    @Override
    public void onCreate() {

        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

        mEventListenerLight = new SensorEventListener() {
            @Override
            public void onSensorChanged(SensorEvent event) {
                float[] values = event.values;
                lastLightValue = values[0];
                createLog();

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

            }
        };

    }

    @Override
    public void onStart(Intent intent,int startId) {
        mSensorManager.registerListener(mEventListenerLight, mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT), SensorManager.SENSOR_DELAY_FASTEST);
    }

    @Override
    public void onDestroy() {
        mSensorManager.unregisterListener(mEventListenerLight);
        super.onDestroy();
    }

    private void createLog() {

        String data = String.valueOf(lastLightValue);

        String file_name = "light_log";
        try {
            FileOutputStream fos = openFileOutput(file_name, MODE_APPEND);
            fos.write(data.getBytes());
            fos.close();
            Toast.makeText(getApplicationContext(), "Message Saved", Toast.LENGTH_SHORT).show();
        } catch (FileNotFoundException e) {
            Toast.makeText(getApplicationContext(), "File not found :" + e, Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            Toast.makeText(getApplicationContext(), "IO exception : " + e, Toast.LENGTH_SHORT).show();
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

1 个答案:

答案 0 :(得分:0)

我不知道在Android中直接查询Sensor按需的方法。 但是,您可以使用两类方法来完成此任务。

创建一个注册LightManager侦听器的单例OnChange,如上所述。在每次更改时,将当前灯值存储在名为lastLightValue的变量中。

而不是LightIntensity类注册Sensor更改,它只会访问LightManager.getInstance().lastLightValue

相关问题