8

Есть класс который следит за данными акселерометра. Если устройство не в движении и экран выключен, то он должен включиться если его взять в руки. Вот код класса

public class Accelerometer {
private Activity activity;
private Fonts fonts;
private Screen2 Screen2;
//
private Integer x = 0;
private Integer y = 0;
private Integer z = 0;
private PowerManager pm;
private PowerManager.WakeLock wl;
private long timer = 0;

public Accelerometer (Activity activity_, Fonts fonts_, Screen2 Screen2_) {
    this.activity = activity_;
    this.fonts = fonts_;
    this.Screen2 = Screen2_;

    pm = (PowerManager) activity.getSystemService(Context.POWER_SERVICE);

    SensorManager sensorManager = (SensorManager) this.activity.getSystemService(Context.SENSOR_SERVICE);
    Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

    sensorManager.registerListener(new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {
            Integer x_ = Math.round(event.values[0]);
            Integer y_ = Math.round(event.values[1]);
            Integer z_ = Math.round(event.values[2]);

            try {
                if (!z_.equals(z)) {
                    x = x_;
                    y = y_;
                    z = z_;
                    // устройство в движении
                    if (!pm.isScreenOn()) { // и экран выключен
                        Log.d("appLog", "wakeup");
                        // включаем экран
                        wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "tag");
                        wl.acquire();
                        if (timer != 0 && System.currentTimeMillis() - timer > 90000) {
                            // если простой больше 1.5 минут - всегда новый опрос
                            activity.dismissDialog(1);
                            clearApp();
                        } else {
                            // если меньше 1.5 минут - то спрашиваем что делать
                            activity.showDialog(1);
                        }
                        wl.release();
                    } else {

                    }
                    timer = 0;
                } else {
                    // устройство не в движении
                    if (timer == 0) {
                        timer = System.currentTimeMillis();
                    }
                }
            } catch (Exception e) {
                Log.d("appLog", "Acc Error");
            }
        }

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

    }, sensor, SensorManager.SENSOR_DELAY_NORMAL);
}}

Но работает он как-то странно, то включается то не включается. Если кабель подключен к компьютеру, то всегда работает так как задумано, а без кабеля при выключенном дисплее акселерометр работает как-то не правильно. Какие тут есть нюансы?

5
  • 1
    Потому, что Ваш телефон переходит в режим сна. А в режиме сна обычное приложение очень быстро "умирает". Когда телефон включается и разблокируется - приложение снова "оживает" (перезапускается). Когда подключено через зарядку/usb то обычно в режим сна не уходит. Что делать? писать сервис, который будет лочить переход в режим сна. Но на подобный код пользователи будут жаловаться сильно-сильно - батарею будет высаживать просто на ура.
    – KoVadim
    30 ноя 2015 в 9:40
  • 1
    Я бы за такие фоновые сервисы руки открывал ) 30 ноя 2015 в 9:49
  • 1
    Смотря для каких целей его использовать. Приложение сугубо индивидуальное. 30 ноя 2015 в 9:55
  • 1
    А нельзя саму ОС как-то настроить что бы она не засыпала при выключении экрана ? 30 ноя 2015 в 9:55
  • 1
    не нужно так делать. Тогда батареи будет хватать на три - четыре часа.
    – KoVadim
    30 ноя 2015 в 13:37

1 ответ 1

1

Акселерометр не является wake-up сенсором, и поэтому нужно самостоятельно удерживать partial wakelock или периодически пробуждать устройство для приёма данных от сенсора для его работы в том режиме который вы хотите.

При подключенном кабеле Android удерживает wakelock - поэтому всё работает, а без кабеля устройство уходит в сон и акселерометр перестаёт работать.

Ознакомьтесь с документацией по сенсорам в режиме сна: Suspend mode

Non-wake-up sensors are sensors that do not prevent the SoC from going into suspend mode and do not wake the SoC up to report data. In particular, the drivers are not allowed to hold wake-locks. It is the responsibility of applications to keep a partial wake lock should they wish to receive events from non-wake-up sensors while the screen is off. While the SoC is in suspend mode, the sensors must continue to function and generate events, which are put in a hardware FIFO. (See Batching for more details.) The events in the FIFO are delivered to the applications when the SoC wakes up. If the FIFO is too small to store all events, the older events are lost; the oldest data is dropped to accommodate the latest data. In the extreme case where the FIFO is nonexistent, all events generated while the SoC is in suspend mode are lost. One exception is the latest event from each on-change sensor: the last event must be saved outside of the FIFO so it cannot be lost.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.