Handler()。postDelayed()在方向改变时发送多个意图

时间:2011-11-30 21:44:40

标签: java android handler orientation-changes postdelayed

好的我正在制作一个暂停1.5秒的启动画面并且效果很好,除了一件事。在timer启动onCreate后,如果配置(方向)发生变化,则timer会重置,然后最终结果会启动ParchmentActivity.java两次。

如何阻止处理程序两次发送意图?

提前致谢!

完整代码可以在@:https://github.com/n00bware/android_apps_parchment

找到

这是我的代码(来自示例http://www.anddev.org/novice-tutorials-f8/splash-fade-activity-animations-overridependingtransition-t9464.html):

public class SplashScreen extends Activity {

private static final int SPLASH_DISPLAY_TIME = 1500;  /* 1.5 seconds */
private static final String TAG = "Parchment";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);

   /* Create a new handler with which to start the main activity
      and close this splash activity after SPLASH_DISPLAY_TIME has
      elapsed. */
   new Handler().postDelayed(new Runnable() {
       @Override
       public void run() {

           Intent parchment = new Intent(SplashScreen.this, ParchmentActivity.class);
           SplashScreen.this.startActivity(parchment);
           SplashScreen.this.finish();
           overridePendingTransition(R.anim.fade_main_in, R.anim.fade_splash_out);
        }
    }, SPLASH_DISPLAY_TIME);
}

/* I found a suggestion to try overriding onConfigurationChanged()
   but it doesn't stop a new timer from being started */

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
}

/* I also tried overriding onStart() but this also doesn't stop a
   new timer. What exactly is called when an orientation configuration
   changes happens? */
@Override
public void onStart() {
    super.onStart();
    setContentView(R.layout.splash);
}

2 个答案:

答案 0 :(得分:1)

您可以创建一个新的静态布尔值,将其设置为false,并且在创建时仅在标志为false时才执行Handler操作...

PS:在if语句中,必须将boolean标志设置为true:)

祝你好运!

答案 1 :(得分:1)

在onCreate中创建处理程序,在onDestroy中释放它,在onStart中发送消息/发布runnable,在onStop中删除message / runnable。

这将在每次旋转时重置计时器,因此如果每秒旋转一次设备,您可能会保持启动画面。

在Android中,切换旋转可能需要一秒左右,您可能需要这种行为,因为它可以启动应用程序,旋转而不会看到启动。