我正在尝试使用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
没有被调用
谢谢你的协助
1条答案
按热度按时间yc0p9oo01#
您的
startActivity(..)
调用在哪里?:)启动新的Activity
是必要的,创建Intent
是不够的