3

I've found code that does what I want, such as:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); 

but this seems to require being in an activity, not a service.

Basically what I want to do is receive the ON_BOOT_COMPLETED intent and start the service, have the service periodically check if (or be notified when, preferably) the screen orientation has changed, and set it back to Landscape.

Is there a way to do this within a service? I've been looking for answers all day and have been unable to find anything, so I apologize profusely if this is a duplicate question.

NOTE: This is a paid freelance project to be used only on devices owned by the person paying me to do the work. It is not for malware or any other such purpose

Caleb Cameron
  • 181
  • 1
  • 15

1 Answers1

5

First of all, the obligatory "please don't do that". I'm hoping that you have a justified reason for doing this, as there's a legitimate way for the user to set this preference by disabling screen rotation.

That said, you cannot do this from a Service. As you point out, Activity.setRequestedOrientation(int) belongs to the Activity class, and cannot be used from any other context.

What you might instead consider doing, is creating a transparent system overlay window, and enforcing it's orientation to landscape instead.

To answer your follow-up question, here's a snippet of code that you can invoke from your service:

private static final boolean DISPLAY = false;

@Override
public void onCreate() {
    final View view = new View(this);
    int dimension = 0;
    int pixelFormat = PixelFormat.TRANSLUCENT;
    if (DISPLAY) {
        view.setBackgroundColor(Color.argb(128, 255, 0, 0));
        dimension = LayoutParams.MATCH_PARENT;
        pixelFormat = PixelFormat.RGBA_8888;
    }
    final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
            dimension, dimension,
            WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
            WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                    | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            pixelFormat);
    params.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
    final WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
    wm.addView(view, params);
}

In the snippet, DISPLAY is a simple switch to enable display of the overlay window for testing purposes. (You should see a half-transparent red overlay.)

Paul Lammertsma
  • 35,234
  • 14
  • 128
  • 182