I am trying to work with SensorEventListener, when phone shake is detected, I want to open a fragment GetInTouchMenuFragment
through activity GetInTouchActivity
onCreate
method of Activity is not called at all. so fragment is not shown.
this is my SensorEventListener
in MainActivity
.
MainActivity
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) {}
}
GetInTouchActivity
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)
}
}
}
Could you please suggest what I am doing wrong here please, why onCreate
in GetInTouchActivity
is not called
Thank you for your assistance R
CodePudding user response:
where is your startActivity(..)
call? :) its necessary to start new Activity
, creating an Intent
is not sufficient
val createdIntent = GetInTouchActivity.createIntent(this@MainActivity)
startActivity(createdIntent)