1

这是我在此的头一篇博文。在问我的问题之前,我想感谢这个网站的团队和所有的贡献者。这里的信息真的帮助了我很多,让我开始为 Android 开发。这是我的问题:我为 DashClock 编写了一个小扩展,它显示根据压力传感器数据计算的当前高度。只要屏幕打开,一切正常。但是当屏幕关闭时,压力传感器会停止输送样品。我尝试了很多但没有成功:设置唤醒锁,注销并重新注册 SensorEventListener,将其放入指定的线程中......有人知道如何让它工作吗?我不需要每秒采样一次,每分钟左右就可以了。以下是我的代码的相关部分:(RTC_WAKEUP -> AlarmReceiver.onReceive -> 启动 SensorService)

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        System.out.println("Alarm!");
        context.startService(new Intent(context, PressureSensorService.class));
    }
}

public class PressureSensorService extends Service implements SensorEventListener {

    final static String SENSOR_UPDATE_ACTION = "SENSOR_UPDATE_ACTION";
    private float pressure;
    private SensorManager mgr;
    private Sensor pressuresensor;
    Intent intent = new Intent("SENSOR_UPDATE_ACTION");
    @Override
    public void onCreate(){
        System.out.println("PressureSensorService created!");
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("PressureSensorService started!");
        mgr = (SensorManager) this.getSystemService(SENSOR_SERVICE);
        pressuresensor = mgr.getDefaultSensor(Sensor.TYPE_PRESSURE);
        mgr.registerListener(this, pressuresensor, SensorManager.SENSOR_DELAY_NORMAL);
        return START_STICKY;
    }
    @Override
    public void onDestroy(){
        mgr.unregisterListener(this, pressuresensor);
        System.out.println("PressureSensorService stopped!");
    }
    @Override
    public void onAccuracyChanged(Sensor arg0, int arg1) {
        // TODO Auto-generated method stub

    }
    @Override
    public void onSensorChanged(SensorEvent event) {
        PressureSensorService.this.pressure = event.values[0];
        intent.putExtra("pressure", pressure);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
        System.out.println("Pressure = "+ pressure + " hPa");
    }
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
}
4

0 回答 0