【问题标题】:Know when rotation is finished using setRequestedOrientation使用 setRequestedOrientation 了解旋转何时完成
【发布时间】:2012-10-17 00:50:41
【问题描述】:

我正在尝试编写一个 .apk 来测量旋转 Android 设备的屏幕需要多长时间(循环几次旋转)。

我正在使用对 setRequestedOrientation() 的调用将屏幕重新定向到 4 个位置(PORTRAITLANDSCAPEREVERSE_PORTRAITREVERSE_LANDSCAPE)。

我的问题是我无法判断轮换何时结束。我尝试了一些解决方案,但每个都有自己的问题。

  1. 我尝试使用onConfigurationChanged()。问题是,当传感器发生方向变化时会触发此方法,而不是来自setRequestedOrientation()。实际上,在我之前调用setRequestedOrientation() 之后,我必须使用FULL_SENSOR 参数调用setRequestedOrientation() 才能使onConfigurationChanged 工作。
  2. 我尝试通过添加一个while 循环来检查屏幕方向(以度为单位),使setRequestedOrientation() 有点“阻塞”。我在setRequestedOrientation() 之前调用了android.view.Display.getRotation() 并用while 循环阻塞,直到它发生变化。不幸的是,它也不起作用。它会在 UI 重新显示之前返回。
  3. 我试图遵循活动的生命周期,等待onCreate() 再次被调用,假设轮换已完成。以前,我一直在循环直到我的计数器达到一个值,在每次迭代中调用setRequestedOrientation()。在这种情况下,我的 while 循环变成了一个 if 语句,我假设 onCreate 每次都会调用该函数,但 onCreate() 在几次迭代后不会被调用。 UI 似乎也没有重新绘制。
  4. 我在网上找到的最终解决方案(但还没有完全实现)是在setRequestedOrientation() 之后使用waitForIdleSync() 方法。 waitForIdleSync() 是 Instrumentation 类的一部分,我认为这只是为了测试而不是标准的 .apk。

非常欢迎任何想法。非常感谢您的帮助。

【问题讨论】:

    标签: android rotation


    【解决方案1】:

    您应该尝试使用: http://developer.android.com/reference/android/view/OrientationEventListener.html

    您需要先调用 enable(),然后您会在设备发生的每次旋转更改时收到通知。

    【讨论】:

      【解决方案2】:

      没有直接的方法可以知道setRequestedOrientation() 何时通过 Android API 完成。唯一知道的方法是在调用它之前和在onCreate() 中调用它之后检查当前方向。

      在你的Activity 课堂上做:

      long timeStamp;
      
      public void onCreate(Bundle savedInstanceState) {
           if (savedInstanceState == null) {
                timeStamp = System.currentTimeMillis();     
           }
           else {
                timeStamp = savedInstanceState.getLong("state_time_stamp");
           }
      
           // For example, check how long it takes to switch from portrait to landscape. 
           // You can modify this part to check PORTRAIT, LANDSCAPE, REVERSE_PORTRAIT and REVERSE_LANDSCAPE.
           final int orientation = getResources().getConfiguration().orientation;    
           if (orientation == Configuration.SCREEN_ORIENTATION_PORTRAIT) {
                setRequestedOrientation(ActivityInfo.ORIENTATION_LANDSCAPE);
                return;
           }
      
           // We will reach here only after setRequestedOrientation() is done
           // and here's the time it took to change the orientation:
           final long elapsedTime = System.currentTimeMillis() - timeStamp; 
      }
      
      public void onSaveInstanceState(Bundle outState) {
           outState.putLong("state_time_stamp", timeStamp);
      }
      

      【讨论】:

        猜你喜欢
        • 2012-04-19
        • 2012-04-01
        • 2017-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-07
        • 1970-01-01
        • 2021-11-23
        相关资源
        最近更新 更多