Well, I finally thank JPM for offering to use handlers, and I decided with this:
public class SplashScreen extends Activity { private static Handler mHandler ; private static Handler mainHandler ; protected static final int CLOSE_SPLASH = 0 ; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.splash_screen); mHandler = new Handler(){ @Override public void handleMessage(Message msg){ switch(msg.what){ case CLOSE_SPLASH: finish(); break; } } }; } @Override public void onStart(){ super.onStart(); if(mainHandler != null){ mainHandler.sendEmptyMessage(MainActivity.START_LOAD); } } @Override public boolean onKeyDown (int keyCode, KeyEvent event){ if(keyCode == KeyEvent.KEYCODE_BACK){ mainHandler.sendEmptyMessage(MainActivity.ABORT_LOAD); } return super.onKeyDown(keyCode, event) ; } public static void setMainHandler(Handler h){ mainHandler = h ; } public static void sendMessage(Message msg){ mHandler.sendMessage(msg); } public static void sendMessage(int w){ mHandler.sendEmptyMessage(w); } }
In MainActivity, I control the back and forth handlers:
public class MainActivity extends Activity { private MainActivity _this; private Handler mHandler; protected static final int FINISH_LOAD = 0 ; protected static final int START_LOAD = 1 ; protected static final int ABORT_LOAD = 2 ; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); _this = this; mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case FINISH_LOAD: SplashScreen.sendMessage(SplashScreen.CLOSE_SPLASH); break; case START_LOAD: initializing(); break; case ABORT_LOAD: finish(); } } }; startSplash(); } private void startSplash() { Intent intent = new Intent(this, SplashScreen.class); SplashScreen.setMainHandler(mHandler); startActivity(intent); } private void initializing() { new Thread() { @Override public void run() { long start_time = android.os.SystemClock.uptimeMillis(); doTheHeavyJob(); long duration = android.os.SystemClock.uptimeMillis() - start_time; if (duration <=3000) { try { wait(3000-duration); } catch (InterruptedException e) { e.printStackTrace(); } } mHandler.sendEmptyMessage(FINISH_LOAD); } }.start(); } }
In this way, I can control the doTheHeavyJob () function and end SplashScreen in both cases: after finishing work and at least after 3000 milliseconds, the minimum duration of my pop-up screen will be shown. I also want to tank Teskio on anddev italian for most of the work done here.
source share