kotlin 如何在SensorEventListener被触发时打开活动/片段

yi0zb3m4  于 2023-01-17  发布在  Kotlin
关注(0)|答案(1)|浏览(99)

我正在尝试使用SensorEventListener,当检测到手机震动时,我想通过活动GetInTouchActivity打开一个片段GetInTouchMenuFragment
活动的onCreate方法根本没有被调用。因此片段没有显示。
这是我的MainActivity中的SensorEventListener
主要活动

override fun onCreate(savedInstanceState: Bundle?) {
 // Getting the Sensor Manager instance
        sensorManager = this.getSystemService(Context.SENSOR_SERVICE) as SensorManager

        Objects.requireNonNull(sensorManager)!!
            .registerListener(sensorListener, sensorManager!!
                .getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL)

}

private val sensorListener: SensorEventListener = object : SensorEventListener {
    override fun onSensorChanged(event: SensorEvent) {

        // Fetching x,y,z values
        val x = event.values[0]
        val y = event.values[1]
        val z = event.values[2]
        lastAcceleration = currentAcceleration

        // Getting current accelerations
        // with the help of fetched x,y,z values
        currentAcceleration = sqrt((x * x + y * y + z * z).toDouble()).toFloat()
        val delta: Float = currentAcceleration - lastAcceleration
        acceleration = acceleration * 0.9f + delta

        // Display a Toast message if
        // acceleration value is over 12
        if (acceleration > 12) {
            Log.d("GetInTouchActivity", "first")
            GetInTouchActivity.createIntent(this@MainActivity)
            Log.d("GetInTouchActivity", "second")
        }
    }
    override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {}
}

获取触控活动

class GetInTouchActivity : InjectionFragmentActivity() {

    @Inject
    lateinit var viewModelFactory: ViewModelProvider.Factory

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.get_in_touch_activity)

        setAppBar(toolbar, showHomeAsUp = true, navIcon = AppBarNavIcon.BACK_ARROW_BLACK)

        if (savedInstanceState == null) {
        Log.d("GetInTouchActivity", "onCreate") // NOT EXECUTED
            showFragment(GetInTouchMenuFragment.newInstance())
        }
    }

    override fun onBackPressed() {
        reporter.reportEvent(javaClass.simpleName.processScreenName(), "Back")

        finish()
    }

    companion object {
        fun createIntent(context: Context): Intent {
            Log.d("GetInTouchActivity", "createIntent") // EXECUTED
            return Intent(context, GetInTouchActivity::class.java)
        }
    }
}

您能指出我在这里做错了什么吗?为什么GetInTouchActivity中的onCreate没有被调用
谢谢你的协助

yc0p9oo0

yc0p9oo01#

您的startActivity(..)调用在哪里?:)启动新的Activity是必要的,创建Intent是不够的

val createdIntent = GetInTouchActivity.createIntent(this@MainActivity)
startActivity(createdIntent)

相关问题