I have a Splashscreen where I am running an animation. Following is my logic regarding moving from Splash screen to MainActivity.
Minimum visible time for Splash screen = minTime
Maximum visible time for Splash screen = maxTime
API is called which gets response in some time - apiTime
1. Show Splash screen for at least minTime.
2. Call an API. If the API's response is received in less than maxtime,
move to next screen immediately otherwise, move to next screen in
maxtime
Following is my code:
public class SplashActivity extends AppCompatActivity {
private ImageView container;
private AnimationDrawable animationDrawable;
int apiTime = 2000, minTime = 1000, maxTime = 5000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
container = findViewById(R.id.iv_icons);
container.setBackgroundResource(R.drawable.splash_animation);
animationDrawable = (AnimationDrawable) container.getBackground();
}
@Override
protected void onResume() {
super.onResume();
animationDrawable.start();
final long start = System.currentTimeMillis();
//calling api in thread simultaneously. As soon as response is received, move to next screen.
//Thread.sleep is just dummy for api response time
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(apiTime);
//if apiTime is less than minTime, then we wait till minTime
long time = minTime - (System.currentTimeMillis() - start);
if (time > 0) {
Thread.sleep(time);
}
moveToNextScreen();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
hardMoveToNextScreen();
}
private void moveToNextScreen() {
Intent i = new Intent(SplashActivity.this, MainActivity.class);
startActivity(i);
finish();
}
private void hardMoveToNextScreen () {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
moveToNextScreen();
}
}, maxTime);
}
}
Now, according to the time values I have used, the thread t1 calls method moveToNextScreen() before method hardMoveToNextScreen() calls the same method. So, once the activity is finished, I should move to MainActivity.
The problem that I am facing is that MainActivity is opening twice. Once from the thread and then from hardMoveToNextScreen() method. But, this should not happen as I am already calling finish() which means that once I move to MainActivity, any method from SplashActivity should not be called anymore.
What am I doing wrong?