1

我正在构建一个需要一直监听加速度计的应用程序,即使应用程序不在前台也是如此。(在这一点上,我想澄清一下,这不是 Play 商店的应用程序。这是一个用于内部使用的特定用途的应用程序,其中电池消耗不是什么大问题 - 另外,如果有人知道另一种方法来检查是否用户正在走路,请告诉我)

为了实现这一点,我创建了一个BroadcastReceiver监听android.intent.action.BOOT_COMPLETED并启动一个注册SensorEventListener. 该服务获得 a 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();
            }
        }
    }
}

我想我提供了从您那里获得帮助所需的所有信息。如果您觉得有一些有用的代码,我将很乐意合作!谢谢

4

0 回答 0