Orientation Heading Inaccuracy

I’m working on an Android application that requires accurate orientation heading updates using the FusedOrientationProviderClient and a custom DeviceOrientationListener. However, I’m experiencing issues with orientation accuracy and incorrect heading values, especially when the device is flat on a surface.

  • When the device is not flat it’s showing almost every time the right heading.

  • If the first value is not accurate,its not fixing itself to the right heading,its just keep updating the wrong heading.

Here’s the class I am using for orientation updates:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class LocationOrientationRepo(context: Context) {
private var deviceOrientationListener: DeviceOrientationListenerImpl? = null
private val fusedOrientationProviderClient: FusedOrientationProviderClient =
LocationServices.getFusedOrientationProviderClient(context)
private val handler = Handler(Looper.getMainLooper())
private val refreshRunnable = object : Runnable {
override fun run() {
checkOrientationListener()
handler.postDelayed(this, REFRESH_INTERVAL_MS)
}
}
private var lastAzimuth: Float? = null
private val threshold = 0.0f // Set your threshold value (in degrees)
fun startListening(onOrientationChanged: (Float) -> Unit) {
if (deviceOrientationListener == null) {
deviceOrientationListener = DeviceOrientationListenerImpl { azimuth ->
if (shouldNotify(azimuth)) {
lastAzimuth = azimuth
onOrientationChanged(azimuth)
}
}
val request = DeviceOrientationRequest.Builder(DeviceOrientationRequest.OUTPUT_PERIOD_DEFAULT).build()
val executor: ExecutorService = Executors.newSingleThreadExecutor()
fusedOrientationProviderClient.requestOrientationUpdates(request, executor, deviceOrientationListener!!)
.addOnSuccessListener {
Log.i(TAG, "Successfully added new orientation listener")
handler.post(refreshRunnable)
}
.addOnFailureListener { e ->
Log.e(TAG, "Failed to add new orientation listener", e)
}
}
}
fun stopListening() {
if (deviceOrientationListener != null) {
Log.i(TAG, "Removing active orientation listener")
fusedOrientationProviderClient.removeOrientationUpdates(deviceOrientationListener!!)
deviceOrientationListener = null
handler.removeCallbacks(refreshRunnable)
}
}
private fun checkOrientationListener() {
if (deviceOrientationListener == null) {
Log.i(TAG, "Orientation listener not active. Restarting.")
startListening { azimuth ->
Log.d(TAG, "Orientation callback with azimuth: $azimuth")
}
}
}
private fun shouldNotify(newAzimuth: Float): Boolean {
// If lastAzimuth is null, initialize it
if (lastAzimuth == null) {
lastAzimuth = newAzimuth
return true
}
// Calculate the difference
val diff = Math.abs(newAzimuth - (lastAzimuth ?: newAzimuth))
return diff >= threshold
}
private inner class DeviceOrientationListenerImpl(private val onOrientationChanged: (Float) -> Unit) :
DeviceOrientationListener {
override fun onDeviceOrientationChanged(deviceOrientation: DeviceOrientation) {
val azimuth = deviceOrientation.headingDegrees
Log.d(TAG, "Device Orientation Changed - Heading: $azimuth") // Debug log for azimuth
onOrientationChanged(azimuth)
}
}
companion object {
private const val TAG = "LocationOrientationRepo"
private const val REFRESH_INTERVAL_MS = 10000L // 10 seconds
}
}
</code>
<code>class LocationOrientationRepo(context: Context) { private var deviceOrientationListener: DeviceOrientationListenerImpl? = null private val fusedOrientationProviderClient: FusedOrientationProviderClient = LocationServices.getFusedOrientationProviderClient(context) private val handler = Handler(Looper.getMainLooper()) private val refreshRunnable = object : Runnable { override fun run() { checkOrientationListener() handler.postDelayed(this, REFRESH_INTERVAL_MS) } } private var lastAzimuth: Float? = null private val threshold = 0.0f // Set your threshold value (in degrees) fun startListening(onOrientationChanged: (Float) -> Unit) { if (deviceOrientationListener == null) { deviceOrientationListener = DeviceOrientationListenerImpl { azimuth -> if (shouldNotify(azimuth)) { lastAzimuth = azimuth onOrientationChanged(azimuth) } } val request = DeviceOrientationRequest.Builder(DeviceOrientationRequest.OUTPUT_PERIOD_DEFAULT).build() val executor: ExecutorService = Executors.newSingleThreadExecutor() fusedOrientationProviderClient.requestOrientationUpdates(request, executor, deviceOrientationListener!!) .addOnSuccessListener { Log.i(TAG, "Successfully added new orientation listener") handler.post(refreshRunnable) } .addOnFailureListener { e -> Log.e(TAG, "Failed to add new orientation listener", e) } } } fun stopListening() { if (deviceOrientationListener != null) { Log.i(TAG, "Removing active orientation listener") fusedOrientationProviderClient.removeOrientationUpdates(deviceOrientationListener!!) deviceOrientationListener = null handler.removeCallbacks(refreshRunnable) } } private fun checkOrientationListener() { if (deviceOrientationListener == null) { Log.i(TAG, "Orientation listener not active. Restarting.") startListening { azimuth -> Log.d(TAG, "Orientation callback with azimuth: $azimuth") } } } private fun shouldNotify(newAzimuth: Float): Boolean { // If lastAzimuth is null, initialize it if (lastAzimuth == null) { lastAzimuth = newAzimuth return true } // Calculate the difference val diff = Math.abs(newAzimuth - (lastAzimuth ?: newAzimuth)) return diff >= threshold } private inner class DeviceOrientationListenerImpl(private val onOrientationChanged: (Float) -> Unit) : DeviceOrientationListener { override fun onDeviceOrientationChanged(deviceOrientation: DeviceOrientation) { val azimuth = deviceOrientation.headingDegrees Log.d(TAG, "Device Orientation Changed - Heading: $azimuth") // Debug log for azimuth onOrientationChanged(azimuth) } } companion object { private const val TAG = "LocationOrientationRepo" private const val REFRESH_INTERVAL_MS = 10000L // 10 seconds } } </code>
class LocationOrientationRepo(context: Context) {

    private var deviceOrientationListener: DeviceOrientationListenerImpl? = null
    private val fusedOrientationProviderClient: FusedOrientationProviderClient =
        LocationServices.getFusedOrientationProviderClient(context)
    private val handler = Handler(Looper.getMainLooper())
    private val refreshRunnable = object : Runnable {
        override fun run() {
            checkOrientationListener()
            handler.postDelayed(this, REFRESH_INTERVAL_MS)
        }
    }

    private var lastAzimuth: Float? = null
    private val threshold = 0.0f // Set your threshold value (in degrees)

    fun startListening(onOrientationChanged: (Float) -> Unit) {
        if (deviceOrientationListener == null) {
            deviceOrientationListener = DeviceOrientationListenerImpl { azimuth ->
                if (shouldNotify(azimuth)) {
                    lastAzimuth = azimuth
                    onOrientationChanged(azimuth)
                }
            }
            val request = DeviceOrientationRequest.Builder(DeviceOrientationRequest.OUTPUT_PERIOD_DEFAULT).build()
            val executor: ExecutorService = Executors.newSingleThreadExecutor()

            fusedOrientationProviderClient.requestOrientationUpdates(request, executor, deviceOrientationListener!!)
                .addOnSuccessListener {
                    Log.i(TAG, "Successfully added new orientation listener")
                    handler.post(refreshRunnable)
                }
                .addOnFailureListener { e ->
                    Log.e(TAG, "Failed to add new orientation listener", e)
                }
        }
    }

    fun stopListening() {
        if (deviceOrientationListener != null) {
            Log.i(TAG, "Removing active orientation listener")
            fusedOrientationProviderClient.removeOrientationUpdates(deviceOrientationListener!!)
            deviceOrientationListener = null
            handler.removeCallbacks(refreshRunnable)
        }
    }

    private fun checkOrientationListener() {
        if (deviceOrientationListener == null) {
            Log.i(TAG, "Orientation listener not active. Restarting.")
            startListening { azimuth ->
                Log.d(TAG, "Orientation callback with azimuth: $azimuth")
            }
        }
    }

    private fun shouldNotify(newAzimuth: Float): Boolean {
        // If lastAzimuth is null, initialize it
        if (lastAzimuth == null) {
            lastAzimuth = newAzimuth
            return true
        }

        // Calculate the difference
        val diff = Math.abs(newAzimuth - (lastAzimuth ?: newAzimuth))
        return diff >= threshold
    }

    private inner class DeviceOrientationListenerImpl(private val onOrientationChanged: (Float) -> Unit) :
        DeviceOrientationListener {

        override fun onDeviceOrientationChanged(deviceOrientation: DeviceOrientation) {
            val azimuth = deviceOrientation.headingDegrees
            Log.d(TAG, "Device Orientation Changed - Heading: $azimuth")  // Debug log for azimuth
            onOrientationChanged(azimuth)
        }
    }

    companion object {
        private const val TAG = "LocationOrientationRepo"
        private const val REFRESH_INTERVAL_MS = 10000L // 10 seconds
    }
}

Issue:

  • Inaccuracy of Orientation Heading:

The heading direction provided by DeviceOrientationListener is not always accurate.
When the device is flat, the heading direction seems incorrect and does not update properly.

  • Sensor Event Issues:

Using sensor events directly also yields inaccurate and erratic results, especially when rotating the device.

What I’ve Tried:
I’ve tried using sensors events but they produce unstable and incorrect values when the device is rotated.
Questions:

  • How can I improve the accuracy of the orientation heading?
  • How can I handle orientation updates correctly when the device is flat?
  • Would you use a different method?

Any guidance or suggestions on how to fix these issues would be greatly appreciated.
Thank you !

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật