I am designing an android application where I need to add the splash screen of my application. Generally I used to use only Activity
upto till now but for this project ADT is creating the Fragment
also with Activity
.
Now I have a confusion where I should write code of timerTask
and Timer
to schedule a task to perform either in onCreate
of the Activity
or onCreateView
method or something else ?
Currently I have written like this but I am not sure it is right or wrong.
public class SplashActivity extends Activity {
// using timer to do operation at certain 3 seconds after.
private Timer mTimer;
private TimerTask mTimerTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
// execute this after 3 seconds
mTimerTask = new TimerTask() {
@Override
public void run() {
// start the activity (Login/Home) depends on the login
// status
}
};
mTimer = new Timer();
mTimer.schedule(mTimerTask, 3000);
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_splash,
container, false);
return rootView;
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
// cancel the timer if user has pressed the back button to abort it.
if(mTimer !=null)
mTimer.cancel();
}
}