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.)