锁定方向,直到Asynctask完成

jlo*_*pez 10 android screen-orientation android-asynctask

只想阻止方向,直到我的视图中加载了所有数据.所以我想到了以下代码,但它不起作用.

private class task extends AsyncTask<String, Void, String> {

   protected String doInBackground(String... params) {
      ...
   }

   protected void onPostExecute(String result) {
      ...
      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
   }

   protected void onPreExecute() {
      ...
      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
   }
}
Run Code Online (Sandbox Code Playgroud)

当我运行这两行SENSOR并且NOSENSOR我的屏幕自动变为水平,而不理解为什么.那可能会发生?

编辑: 我将以下行检查当前方向,结果如下:

   protected void onPreExecute() {
        if (getResources().getConfiguration().orientation==Configuration.ORIENTATION_LANDSCAPE) {
            Log.e("TAG","LANDSCAPE");
        }else{
            Log.e("TAG","PORTRAIT");
        }
      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
   }
Run Code Online (Sandbox Code Playgroud)

Logcat的结果:

LANDSCAPE
Run Code Online (Sandbox Code Playgroud)

但是,如果我删除两行(SetRequestedOrientation),我在logcat中得到这个:

PORTRAIT
Run Code Online (Sandbox Code Playgroud)

use*_*305 6

只需更换setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);

让我知道发生了什么......

入门级

 protected void onPreExecute() {
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
}
Run Code Online (Sandbox Code Playgroud)

在退出等级

 protected void onPostExecute(String result) {
      ...
     setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
   }
Run Code Online (Sandbox Code Playgroud)

更新:

有线行为(在你的情况下)但是,你可以用任何方式获得当前的方向,

int currentOrientation = getResources().getConfiguration().orientation; 
Run Code Online (Sandbox Code Playgroud)

现在将此方向设置为onPreExecute()..

喜欢,

protected void onPreExecute() {
  ...
  int currentOrientation = getResources().getConfiguration().orientation; 
   if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
   }
   else {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
   }
}
Run Code Online (Sandbox Code Playgroud)

简单...... :-)