Android 运动传感器侦听器在 1 分钟后被杀死

Android motion sensor listener gets killed after 1 minute

我想要一个可以从 MotionSensors 接收事件更新的应用程序,即使该应用程序在后台也是如此。问题是如果应用程序在后台运行一分钟,android 会终止任何服务。

val sensorsManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
sensorManager.registerListener( .. )

有谁知道解决此问题的简单方法?使用代码或更好的方法,禁用 android 上的某些设置。谢谢

首先,为了运行它永久,必须有一个通知它是运行宁permanently.This通知是永久的,你不能从通知部分。

Service.kt

private fun parmanentNotification() {
        val notification=NotificationCompat.Builder(this,channelId)
            .setSmallIcon(R.drawable.ic_stat_name)
            .setContentTitle("The application is running")
            .setContentText("Android motion sensor working")
            .build()
        startForeground(1,notification)
    }

这就是我们开始服务的方式

@RequiresApi(Build.VERSION_CODES.M)
    override fun onStart() {
        val notificationIntent = Intent(this, YouServiceName::class.java)
        startService(notificationIntent)
        super.onStart()
    }