You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android光强服务修改需求:调用时写入传感器实时值而非变化触发

Fix: LightIntensity Service Writes Value Only When Invoked

Got it, let's tweak this Service so it writes the current light sensor value only when you call the Service, instead of spamming the log every time the sensor reading changes. Here's the refactored code and breakdown of the changes:

Refactored Code

public class LightIntensity extends Service {
    private SensorManager mSensorManager;
    private SensorEventListener mEventListenerLight;
    private float currentLightValue;

    @Override
    public void onCreate() {
        super.onCreate();
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        // Initialize listener to capture just one reading
        mEventListenerLight = new SensorEventListener() {
            @Override
            public void onSensorChanged(SensorEvent event) {
                currentLightValue = event.values[0];
                // Write value immediately after getting it
                createLog(currentLightValue);
                // Unregister right away to stop listening
                mSensorManager.unregisterListener(this);
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int accuracy) {
                // No action needed here
            }
        };
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Register listener temporarily when Service starts
        Sensor lightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
        if (lightSensor != null) {
            mSensorManager.registerListener(mEventListenerLight, lightSensor, SensorManager.SENSOR_DELAY_NORMAL);
        } else {
            Toast.makeText(getApplicationContext(), "Light sensor not available", Toast.LENGTH_SHORT).show();
        }
        // Don't auto-restart Service if it's killed
        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        // Clean up listener just in case it's still registered
        mSensorManager.unregisterListener(mEventListenerLight);
        super.onDestroy();
    }

    private void createLog(float lightValue) {
        String data = String.valueOf(lightValue) + "\n"; // Add newline for readability
        String file_name = "light_log";
        try {
            FileOutputStream fos = openFileOutput(file_name, MODE_APPEND);
            fos.write(data.getBytes());
            fos.close();
            Toast.makeText(getApplicationContext(), "Light intensity saved", Toast.LENGTH_SHORT).show();
        } catch (FileNotFoundException e) {
            Toast.makeText(getApplicationContext(), "File not found: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            Toast.makeText(getApplicationContext(), "IO error: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

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

Key Changes Explained

  • Temporary Sensor Listening: Instead of keeping the sensor registered nonstop, we now register it only when the Service starts, capture one reading, then immediately unregister. This ensures we only get the current value at invocation time.
  • Replaced Deprecated onStart: Switched to onStartCommand (the modern replacement for onStart) which gives better control over Service lifecycle behavior. We return START_NOT_STICKY since we don't need the Service to restart automatically if it's killed.
  • Improved Log Readability: Added a newline to each log entry so values don't run together in the file.
  • Sensor Availability Check: Added a check for the light sensor to avoid null pointer exceptions on devices without this sensor.

How to Use

Every time you start this Service via an Intent:

Intent intent = new Intent(context, LightIntensity.class);
startService(intent);

It will grab the current light sensor value and write it to the log file once.

内容的提问来源于stack exchange,提问作者Huda Malik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:05:16