在“待机”期间保留SensorEventListener

时间:2013-01-04 14:22:51

标签: android accelerometer android-sensors wakelock standby

即使应用程序不在前台,我正在构建一个需要始终收听加速度计的应用程序。 (此时,我想澄清一下,这不是Play商店的应用程序。这是一个具有内部使用特定用途的应用程序,电池耗尽不是问题 - 另外,如果有人知道另一种方法来检查是否用户正在走路,请让我知道)

为实现这一目标,我创建了一个BroadcastReceiver来监听android.intent.action.BOOT_COMPLETED并启动一个注册SensorEventListener的服务。该服务获得PARTIAL_WAKE_LOCK,我希望通过此锁定,SensorEventListener仍会收到onChange()回调,但这种情况不会发生。但是,FULL_WAKE_LOCK它有效 - 但我不想保持屏幕,用户也可以按待机按钮... 在我的调试会话中,我从未看到服务被破坏,因此,永远不应该释放唤醒锁。

这是获取锁并注册传感器的Service类:

public class WalkingDetectorService extends Service {

    private static PowerManager.WakeLock wakeLock = null;
    private static final String LOCK_TAG = "WALKING_DETECTOR";

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

    @Override
    public void onCreate() {
        super.onCreate();
        acquireLock(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
            // started on boot from a BroadcastReceiver
        startMotionDetector(getApplication());
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        releaseLock();
        super.onDestroy();
    }

    private void startMotionDetector(Application application) {

        int sensitivityIdx = SettingsManager.getInt(application, SettingsManager.SETTING_SENSOR_SENSITIVITY);

        if (sensitivityIdx == -1) {
            sensitivityIdx = MotionSensor.DEFAULT_SENSITITY_IDX;
        }

        float fSens = MotionSensor.getSensivity(sensitivityIdx);

        //SensorEventListener is registered here. It is properly done. Only stops listen when screen goes off (by timeout or user pressing the standby button)
            MotionSensor.startMotionSensor(application, fSens);

    }

    public static synchronized void acquireLock(Context ctx) {
        if (wakeLock == null) {
            PowerManager mgr = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
            wakeLock = mgr.newWakeLock(PowerManager.FULL_WAKE_LOCK, LOCK_TAG);
            wakeLock.setReferenceCounted(true);
        }
        wakeLock.acquire();
    }

    public static synchronized void releaseLock() {
        if (wakeLock != null) {
            if (wakeLock.isHeld())
            {
                wakeLock.release();
            }
        }
    }
}

我想我提供了从您那里获得帮助所需的所有信息。 如果您觉得某些代码有用,我将很乐意为您精心准备!谢谢

0 个答案:

没有答案