2

TL;DR 我怎样才能让 Android 传感器为我的应用程序永久运行/激活/注册,即使我关闭它?

目标:
我正在制作一个 Flutter 应用程序,它使用计步器包计算您的步数,
该包使用Android的内置传感器TYPE_STEP_COUNTER
返回自上次启动 (iOS) 以来采取的步数。在 Android 上,安装应用程序之前采取的任何步骤都不会计算在内。

我是如何实现的:

  • 当应用程序在前台主动运行时,每一步都会导致 amyStepCount增加 1。
  • 在所有其他情况下(手机锁定、进入主屏幕、关闭应用程序...),androidTYPE_STEP_COUNTER传感器仍应在后台运行stepCount,一旦我再次打开我的应用程序,新的和上次保存的区别stepCount(保存使用 shared_prefs) 将被计算并添加到myStepCount.

重要提示:
传感器TYPE_STEP_COUNTER必须在后台永久运行/保持注册,即使在我锁定手机、转到主屏幕或关闭应用程序后...

观察:

  • 在我的三星 Galaxy A02s 上,我的应用程序运行良好,正如它应该的那样(如上所述)。那是因为在那部手机上我还安装了 Google Fit 应用程序,它可以 24/7 跟踪您的步数(因此 TYPE_STEP_COUNTER传感器被永久注册)。
  • 在我的三星 Galaxy S7 上,我的应用程序无法正常运行。 myStepCount当我在应用程序在前台运行时采取措施时会增加。但是,一旦我再次打开应用程序,将不会添加应用程序关闭时采取的步骤。注意:我在这款手机上没有任何其他计步应用,例如 Google Fit。myStepCount

结论:
我需要找到一种方法TYPE_STEP_COUNTER从我的 Flutter 应用程序中注册传感器,并且即使在我关闭应用程序后也保持注册状态。

2 尝试(但不成功)的解决方案:

第一次尝试:
从我的 Flutter 代码中调用原生 Android 代码来注册传感器
这是我的main.dart文件(为简单起见,省略了不重要的部分):

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(App());
}

class App extends StatefulWidget {
  @override
  _AppState createState() => _AppState();
}

class _AppState extends State<App> with WidgetsBindingObserver {

  @override
  void initState() {
    super.initState();

    if (Platform.isAndroid) {
      _activateStepCounterSensor();
    } else if (Platform.isIOS) {
      //TODO check if anything is needed to to here
    }
  }

  void _activateStepCounterSensor() async {
    MethodChannel _stepCounterChannel = MethodChannel('com.cedricds.wanderapp/stepCounter'); //convention
    dynamic result = await _stepCounterChannel.invokeMethod('activateStepCounterSensor');
    switch (result) {
      case "success":
        //The following line gets printed when I run the flutter app on my Samsung Galaxy S7:
        print('_activateStepCounterSensor(): successfully registered step counter sensor for android');
        break;
      case "error":
        print('_activateStepCounterSensor(): failed to register step counter sensor (not available) for android');
        //TODO display errorpage (because app is completely useless in this case)
        break;
      default:
        print('_activateStepCounterSensor(): unknown result: $result');
        break;
    }
  }

  //build() and other lifecycle-methods and helper methods: not important for this question
}

这是我的MainActivity.kt文件:

package com.cedricds.wanderapp

import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.util.Log
import android.widget.Toast
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel

class MainActivity2: FlutterActivity(), SensorEventListener {

    private val STEP_COUNTER_CHANNEL = "com.cedricds.wanderapp/stepCounter";
    private lateinit var channel: MethodChannel

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)

        channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, STEP_COUNTER_CHANNEL)
        channel.setMethodCallHandler { call, result ->
            when(call.method){ //this is like switch-case statement in Java
                "activateStepCounterSensor" -> {
                    activateStepCounterSensor(result)
                }
            }
        }
    }

    private var sensorManager : SensorManager?=null
    private var sensor: Sensor ?= null

    private fun activateStepCounterSensor(result: MethodChannel.Result) {
        //This line gets printed when I run the flutter app, so the method gets called successfully:
        Log.d("Android", "Native Android: activateStepCounterSensor()")
        
        sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
        sensor = sensorManager?.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)
        if (sensor == null) {
            Toast.makeText(this, "missing hardware.", Toast.LENGTH_LONG).show()
            result.error("error", "error", "error")
        } else {
            sensorManager?.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL)
            //This line gets printed:
            Log.d("Android", "Native Android: registered TYPE_STEP_COUNTER")
            //and never unregister that listener
            result.success("success")
        }
    }

    override fun onSensorChanged(p0: SensorEvent?) {}
    override fun onAccuracyChanged(p0: Sensor?, p1: Int) {}
}

尽管数量很少print(...)并且Log.d(...)按预期在控制台中打印,但该应用程序无法按我预期的方式运行。当我退出应用程序时,例如走 50 步,然后再次打开应用程序,那 50 步就不见了。似乎传感器在某处未注册。

第二次尝试:
通过删除修改计步器包的代码unregisterListener(...):我对文件所做的唯一更改是 2Log.d(...)条语句,更重要的是,注释掉了特定的代码行。

SensorStreamHandler.kt从计步器包修改:

package com.example.pedometer

import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.Looper
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.EventChannel
import android.os.Handler
import android.util.Log

class SensorStreamHandler() : EventChannel.StreamHandler {

    private var sensorEventListener: SensorEventListener? = null
    private var sensorManager: SensorManager? = null
    private var sensor: Sensor? = null
    private lateinit var context: Context
    private lateinit var sensorName: String
    private lateinit var flutterPluginBinding: FlutterPlugin.FlutterPluginBinding

    constructor(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding, sensorType: Int) : this() {
        this.context = flutterPluginBinding.applicationContext
        this.sensorName = if (sensorType == Sensor.TYPE_STEP_COUNTER) "StepCount" else "StepDetection"
        sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
        sensor = sensorManager!!.getDefaultSensor(sensorType)
        this.flutterPluginBinding = flutterPluginBinding
    }

    override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
        Log.d("Pedometer", "Native Android: onListen()")
        if (sensor == null) {
            events!!.error("1", "$sensorName not available",
                    "$sensorName is not available on this device");
        } else {
            sensorEventListener = sensorEventListener(events!!);
            sensorManager!!.registerListener(sensorEventListener, sensor, SensorManager.SENSOR_DELAY_NORMAL);
        }
    }

    override fun onCancel(arguments: Any?) {
        Log.d("Pedometer", "Native Android: onCancel()")
        
        //The only change I did: commenting out the following line:
//        sensorManager!!.unregisterListener(sensorEventListener);
    }

}

这也没有解决我的问题。因此,如果有人知道我如何在我的颤振应用程序中永久注册 TYPE_STEP_COUNTER 传感器,请告诉我。

4

1 回答 1

1

更新:我联系了计步器包的一位开发人员,他建议我使用flutter_foreground_service(由与计步器相同的团队/公司开发)。有用。

但如果有另一种方法(可能类似于我的 2 次失败尝试),我仍然会觉得它很有趣。

于 2022-02-09T22:13:23.387 回答