Reputation: 561
I was trying to make a very simple app which has a splash screen leading to the main activity. Can someone please point out why the splash screen's sleep continues indefinitely? If I remove the sleep functionality, the app works properly.
Splash class:
package com.example.myfirstapp.app;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class Splash extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread timer = new Thread(){
@Override
public void run() {
super.run();
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent open = new Intent("android.intent.action.MAINACTIVITY");
startActivity(open);
}
}
};
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.myfirstapp.app.Splash"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.myfirstapp.app.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAINACTIVITY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
Upvotes: 1
Views: 76
Reputation: 54781
You're not starting the thread. That's the answer to the question, but you really should not be starting a thread for this.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
new Handler().postDelayed(new Runnable(){
@Override
public void run() {
Intent intent = new Intent(this, com.example.myfirstapp.app.MainActivity.class);
startActivity(intent);
finish();
}
}, 1000);
}
I have also shown you a better way of starting the activity (not by string), and I call finish()
to close the splash screen so that when they press back it doesn't show the splash again.
A quick note on threads
Threads are expensive, they take time and memory to spin up. So spinning them up for a one off task never makes sense. In addition, the code that runs on them requires threadsafety considerations, whereas my solution will run on the same ui thread that requested it to run later. If you do require code to run in parallel (and here you don't) I'd still recommend in 99% of cases you use AsyncTask
over thread.
Upvotes: 2