2017-06-02 15 views
0

本质上,我有两个活动之间的可运行切换。我在onCreate runnable中有一个计时器,它在主活动中设置为0毫秒,并立即切换到启动画面。启动画面仅仅是一个imageview,然后使用类似的可运行程序在3000毫秒后向右切换。如何简化这个java启动画面?

我的问题是这样的;我可以简化主要活动上的代码吗?如果我想立即加载SplashScreen.activity,是否真的需要.postdelayed?

如果延迟没有必要,我该如何正确摆脱它,以便应用程序立即加载splashscreen?

主要活动:

 /* 
     SPLASH SCREEN 
     */ 

     splashScreenRun = settings.getBoolean("splashScreenRun", splashScreenRun); 

     if (splashScreenRun == true) { 

      settings.edit().putBoolean("splashScreenRun", false).commit(); 

      new Handler().postDelayed(new Runnable() { 
       @Override 
       public void run() { 

        Intent splashIntent = new Intent(MainActivity.this, SplashActivity.class); 
        startActivity(splashIntent); 
        finish(); 

       } 

      },0); 

     } 
     else { 

      settings.edit().putBoolean("splashScreenRun", true).commit(); 

     } 

     //END 

然后是闪屏:

所有的
@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_splash); 

     //splash screen 
     new Handler().postDelayed(new Runnable(){ 
      @Override 
      public void run(){ 

       Intent splashEndIntent = new Intent(SplashActivity.this, MainActivity.class); 
       startActivity(splashEndIntent); 
       finish(); 

      } 

     },splashTimeout); 
     //end splash screen 
+0

你可以使用onStart()来做到这一点,并且没有必要使用postdelayed。 –

回答

0

首先从未使用匿名处理。使用处理程序对象。

Handler handler = new Handler(); 
    runnable = new Runnable() { 
    @Override 
    public void run() {  
     startActivity(new 
     Intent(SplashActivity.this, MainActivity.class));        
     overridePendingTransition(R.anim.right_in, R.anim.right_out);           
     finish();        
     }}; 
    handler.postDelayed(runnable, 3000); 

并在摧毁

@Override 
protected void onDestroy() { 
    super.onDestroy(); 
    handler.removeCallbacks(runnable); 
} 

这将阻止应用崩溃,如果用户直接从任务管理器关闭应用程序。

OR

您应该使用

runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
        //Do your stuff here. 
        } 
       }); 

希望这有助于。