Android How to - Lock Activity








Question

We would like to know how to lock Activity.

Answer

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
/*  ww  w . j  a va2 s .c  om*/
class ActivityUtils {
  public static int lockActivityOrientation(Activity activity) {
    int oldOrientation = activity.getRequestedOrientation();

    int currentOrientation = activity.getResources().getConfiguration().orientation;
    if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
      activity
          .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
    } else {
      activity
          .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
    }

    return oldOrientation;
  }

  public static void unlockActivityOrientation(Activity activity,
      int orientation) {
    activity.setRequestedOrientation(orientation);
  }

}