I have a question that I have a splash screen in my android app in which I am using thread to wait for 8 seconds, it is running fine in 1.6,2.1,2.2,2.3.3, 3.0, 3.1 but returns error when I want to run the same in 4.0.3 version of android, I don't know why? Please suggest me the right solution for the same. Below I mentioned error stack and my code also.
Error Stack:
01-05 10:16:06.417: E/AndroidRuntime(589): FATAL EXCEPTION: Thread-75
01-05 10:16:06.417: E/AndroidRuntime(589): java.lang.UnsupportedOperationException
01-05 10:16:06.417: E/AndroidRuntime(589): at java.lang.Thread.stop(Thread.java:1076)
01-05 10:16:06.417: E/AndroidRuntime(589): at java.lang.Thread.stop(Thread.java:1063)
01-05 10:16:06.417: E/AndroidRuntime(589): at com.shipface.common.SplashScreen$1.run(SplashScreen.java:34)
Code:
public class SplashScreen extends Activity {
/** Called when the activity is first created. */
Thread splash;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
splash = new Thread(){
@Override
public void run(){
try {
synchronized(this){
// Wait given period of time or exit on touch
wait(4000);
Intent intent = new Intent(SplashScreen.this,HomeActivity.class);
startActivity(intent);
finish();
}
}
catch(InterruptedException ex){
}
finish();
stop();
}
};
splash.start();
}
}
Everybody's already said where the exception is coming from (Thread.stop()
), so I'll leave that alone...
By far, the easiest method is to not create a Thread
for this purpose at all; even an AsyncTask
is over-doing it. This is what the Handler
was created for (or even CountDownTimer
, but Handler
is cleaner, IMO).
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Handler handler = new Handler();
Runnable action = new Runnable(){
@Override
public void run(){
Intent intent = new Intent(SplashScreen.this,HomeActivity.class);
startActivity(intent);
finish();
}
};
handler.postDelayed(action, 8000);
}
The Handler
will even run the action on the main thread for you, where that code should pretty much be called anyway.
HTH
Thread.stop is deprecated method which is the reason you are getting exception. It will work on lower versions with a warning. Try using AsyncTask instead of threads. They are much safer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With