Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Splash screen for "Application" class

I have an Android app where I've extended the base Application class in order to set up some global variables.

public class MyApplication extends Application {

 private ArrayList<ModelClass> master_list; // global variable 1
 private DataBaseHelper db_helper; // global variable 2

 @Override
 public void onCreate() {
  super.onCreate();
  //do database work that will take about 5 seconds
 }
}

I'd like to show a splash screen to the user while the Application class is working (i.e. before my Main Activity is created). Is there a way to do this?

like image 813
user141146 Avatar asked Sep 30 '10 19:09

user141146


2 Answers

You could make the SplashActivity your start activity.

When MyApplication has completed it's work you could start your main activity and dispose the splash screen.

But don't do the heavy database work in onCreate, create another function and do it there, otherwise your splash activity won't be shown.

public class SplashActivity extends Activity
    @override
    protected void onResume() {
    //Create a thread
    new Thread(new Runnable() {
            public void run() {
                //Do heavy work in background
                ((MyApplication)getApplication()).loadFromDb();
                startActivity(new Intent(SplashActivity.this, MainActivity.class));
                finish(); //End this activity
            }
        }).start();
    }
}
like image 183
MatteKarla Avatar answered Oct 20 '22 12:10

MatteKarla


The way I do this in my apps is by having your main activity extend ActivityGroup.

public class App extends ActivityGroup {
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.splashscreen);
        new Thread(new Runnable() {
            public void run() {
                // do your loading here
                final LocalActivityManager lam = getLocalActivityManager();
                runOnUiThread(new Runnable() {
                    public void run() {
                        Intent mainIntent = new Intent(MainActivity.class, App.this);
                        Window w = lam.startActivity("main", mainIntent);
                        setContentView(w.getDecorView());
                    }
                }
            }
        }, "App loading thread").start();
    }
}

This way, when the app resumes you immediately get the app, not the splash screen, and you only load your data once (when the app starts).

I actually use this to make sure the user is logged in when the app starts, and if the username/password combination is not right I don't start the main app, but a login screen :)

like image 45
Thomas Vervest Avatar answered Oct 20 '22 12:10

Thomas Vervest