Friday 1 January 2016

Splash Activity Loading Screen in Android


Hello, Loading screen is important for all of the apps, during the splash screen it can use to prepare all the needed information and the most common one is database.

In this post it will teach you how to create a splash screen in Android.

First create a new project and select empty activity template.

Then, add a text "main activity" on the main layout xml file just to indicate that it's a UI of the main activity class.

Now create a new layout file and name it splash and add a text "loading......" on it just to indicate it's the loading screen.

Next create a new java class and name it splash and extend it with Activity.

Then add this code inside this splash class

private static final int SPLASH_SHOW_TIME = 4800;

@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.splash);
new BackgroundSplashTask().execute();
}

private class BackgroundSplashTask extends AsyncTask<Void, Void, Void> {

@Override
protected void onPreExecute(){
super.onPreExecute();
}

@Override
protected Void doInBackground(Void... arg0) {
try {
Thread.sleep(SPLASH_SHOW_TIME);
} catch (InterruptedException e) {
e.printStackTrace();
} return null;
}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Intent i = new Intent(splash.this, MainActivity.class);
startActivity(i); finish();
}

}

The code above is using AsyncTask it's use to run the function in sequence, AsyncTask is important to use when to do some task that mess with internet network or some time consume task, it's need to wait until all the information is loaded only continue the next process.

Next go to Android Manifest file and replace the android activity name from .MainActivity to .splash because we want to load the splash activity first when the app is on. Then register the main activity class in the Android Manifest file, just add this code under the application tag

<activity android:name=".MainActivity"
android:label="@string/app_name"/>

Video Tutorial: Click here

No comments:

Post a Comment