Android Question Programmatically inhibit screen rotation from a service

swChef

Active Member
Licensed User
Longtime User
Android settings has an option to enable/disable screen rotation, retaining the current orientation.

From a Service (not an application), is it possible to programmatically change that enable/disable state?

I've dug around for a while but did not find any discussion of such, just the per-activity settings.

Thanks
-Chris
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
You can change it programmatically from an Activity with Phone.SetScreenOrientation.

You can globally disable the auto rotate feature with this code:

Manifest editor:
B4X:
AddPermission(android.permission.WRITE_SETTINGS)

B4X:
Sub AutoRotateEnabled(Enabled As Boolean)
   Dim context As JavaObject
   context.InitializeContext
   Dim value As Int
   Dim jo As JavaObject
   If Enabled Then value = 1 Else value = 0
   jo.InitializeStatic("android.provider.Settings.System").RunMethod("putInt", Array(context.RunMethod("getContentResolver", Null), _
     "accelerometer_rotation", value))
End Sub

This can be called from a service or activity.
 
Upvote 0

swChef

Active Member
Licensed User
Longtime User
Thank you, Erel. And for those who need to check the current state:

B4X:
Sub GetAutoRotate As Boolean
    Dim context As JavaObject
    context.InitializeContext
    Dim jo As JavaObject
    Dim value As Int = jo.InitializeStatic("android.provider.Settings.System") _
     .RunMethod("getInt", Array As Object(context.RunMethod("getContentResolver", Null) _
     , "accelerometer_rotation"))
     Return (value=1)
End Sub
 
Upvote 0

vangogh

Active Member
Licensed User
Longtime User
I set

B4X:
#Region  Project Attributes
    #SupportedOrientations: landscape
#End Region

so the device DOES NOT rotate automatically when you rotate the device


and then I manage the rotation by code, when I want e.g.


B4X:
Dim p As Phone
p.SetScreenOrientation(1) 'portrait
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…