这是我解决这个问题:
@Override
protected void onPreExecute() {
Device.lockOrientation((Activity)context);
...
}
@Override
protected void onPostExecute(List<Hydrant> hydrants) {
Device.releaseOrientation((Activity)context);
...
}
设备实现:
public class Device {
public static void lockOrientation(Activity activity) {
Display display = ((WindowManager) activity.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int rotation = display.getRotation();
int tempOrientation = activity.getResources().getConfiguration().orientation;
int orientation = 0;
switch(tempOrientation)
{
case Configuration.ORIENTATION_LANDSCAPE:
if(rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_90)
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
else
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
break;
case Configuration.ORIENTATION_PORTRAIT:
if(rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_270)
orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
else
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
}
activity.setRequestedOrientation(orientation);
}
public static void releaseOrientation(Activity activity) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
}
由于AsyncTasks只是为了几秒钟运行,这是一个可以接受的解决方案对我来说这很少会影响用户。特别是有一些ProgressDialog可以很好地表明她需要等待多长时间。