1

I am trying to record pressure data on a Samsung N7100. My problem is that the onSensorChanged() Method won't be called after the screen has gone dark. On screen on everything starts working fine again. Can anybody point me in the right direction? Tried setting a wakelock, running the service in foreground, re-register the listener, ...., nothing works. Please help :-)

//MainActivity starts service (this is just a test, not the real app I am building)

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    startService(new Intent(this, sensorservice.class));
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

And here's the service:

public class sensorservice extends Service implements SensorEventListener{

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate() {

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Notification noti = new Notification.Builder(this)
    .setContentTitle("test")
    .setContentText("test")
    .setSmallIcon(R.drawable.ic_launcher)
    .setOngoing(true)
    .build();
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    startForeground(5, noti);
    PowerManager pm = (PowerManager)this.getSystemService(sensorservice.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"Tag");
    wl.acquire();
    SensorManager mgr = (SensorManager) this.getSystemService(SENSOR_SERVICE);
    Sensor pressuresensor = mgr.getDefaultSensor(Sensor.TYPE_PRESSURE);
    mgr.registerListener(this, pressuresensor, SensorManager.SENSOR_DELAY_NORMAL);
    return START_STICKY;
}

@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
    // TODO Auto-generated method stub

}

@Override
public void onSensorChanged(SensorEvent event) {
    float pressure = event.values[0];
    System.out.println("Pressure = "+ pressure + " hPa");       
}

}
Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
PaulSimon
  • 35
  • 1
  • 4
  • Is the `sensorservice ` still active when the screen switches off? – Aleksander Lidtke Nov 10 '13 at 12:28
  • Yes, it is. In my real application the service is started by an alarm receiver. I can see the System.out... messages of the service being started while the screen is off. But the onSensorChanged() method of the SensorListener never gets called. When I turn on the screen the pressure sensor instantly starts providing data again. – PaulSimon Nov 10 '13 at 14:45

0 Answers0