WearOS Off Body 事件并不总是触发

问题描述 投票:0回答:1

我正在为 WearOS 开发一个简单的应用程序。该应用程序由应用程序本身组成,仅显示一个图像和两个服务。一个是一项服务,进行 NFC 卡模拟,另一个只是监听离体事件,并在手表摘下时重置一些值。这在我调试时效果很好,在正常启动时也能运行一段时间。

但是,几个小时后,手表可以摘下,而我的应用程序没有收到该事件。我怀疑,尽管有

START_STICKY
标志,操作系统正在终止该服务并且没有重新启动它。手表未与手机连接,也未运行其他应用程序。

这是我的服务代码:

public class MySensorService extends Service
{
    private static final String TAG = "MySensorService";

    private SensorManager sensorManager;
    private Sensor mOffBody;

    public MySensorService()
    {
        Log.i(TAG, "Sensor service was created.");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        Log.i(TAG, "Sensor service starting.");

        sensorManager = (SensorManager) getApplicationContext().getSystemService(SENSOR_SERVICE);
        mOffBody = sensorManager.getDefaultSensor(TYPE_LOW_LATENCY_OFFBODY_DETECT, true);
        if (mOffBody != null) {
            sensorManager.registerListener(mOffbodySensorListener, mOffBody,
                    SensorManager.SENSOR_DELAY_NORMAL);
        }
        Log.i(TAG, "Sensor service was started.");
        return START_STICKY;
    }

    private void onWatchRemoved()
    {
        Log.i(TAG, "Watch is not worn anymore");
        Intent intent = new Intent(this, MyAPDUService.class);
        intent.putExtra("UserID", 0);
        Log.d(TAG,"starting service");
        startService(intent);
    }

    private void onWatchAttached()
    {
        Log.i(TAG, "Watch is now worn");
    }

    private final SensorEventListener mOffbodySensorListener = new SensorEventListener()
    {
        @Override
        public void onSensorChanged(SensorEvent event)
        {
            if (event.values.length > 0)
            {
                if (event.values[0] == 0) // 0 = Watch is not worn; 1 = Watch is worn
                {
                    onWatchRemoved();
                }
                else
                {
                    onWatchAttached();
                }
            }
        }

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

        }
    };

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        Log.i(TAG, "Sensor Service destroyed");
    }
}
java android android-service wear-os android-sensors
1个回答
0
投票

看起来你的手腕检测逻辑是正确的。服务可能有问题。

请参阅以下参考资料了解离体事件的详细信息 https://developer.samsung.com/sdp/blog/en/2023/06/14/detect-when-a-galaxy-watch-is-being-worn

尝试将您的服务设置为带有通知的前台服务。后台服务不保证无限运行。如果您想使用此服务运行几个小时,我认为您需要将其用作前台服务。

val intent = Intent(...) // Build the intent for the service
context.startForegroundService(intent)

请参考以下更多信息。 https://developer.android.com/develop/background-work/services/foreground-services

© www.soinside.com 2019 - 2024. All rights reserved.