miannelle
miannelle

Reputation: 231

Android Splash Screen causing ANR

I am using the following splash screen code with an onTouchEvent method. I am getting ANR's and do not know what to do. The app works perfectly, except occasionally it locks up with a Sorry, Activity xxx is not responding. Any ideas?

   _splashTime = 5000 ; // approx 5 seconds
   public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        _active = false;
    }
    return true;
   }

  Thread splashTread = new Thread() {
  @Override
  public void run() {
    try {
        int waited = 0;
        while(_active && (waited < _splashTime )) 
        {
            sleep( _waitsecs );
            if  ( _active ) {
                waited += _waitsecs ;
            }
        }
    } 
    catch(InterruptedException e) {
        // do nothing with catch
    } 
    finally {
        start_program();
        finish();
    }
}
 };
splashTread.start();

Upvotes: 0

Views: 996

Answers (2)

Piyush Patel
Piyush Patel

Reputation: 1825

This is very simpler solution for timer based task. go through it.

    TimerTask timerTask;
    Timer timer;

    timerTask = new TimerTask() {

        @Override
        public void run() {
            // after 3 seconds this statement excecutes
            // write code here to move to next screen or
            // do next processing.
        }
    };

    timer = new Timer();
    timer.schedule(timerTask, 3 * 1000); // 3 seconds

This way won't create ANR if you use it proper way.

-Thanks

Upvotes: 2

Bernd
Bernd

Reputation: 938

The problem with the Activity is not responding arises when an activity has not finish an operation within 5 seconds. This is probably the reason why it sometimes comes and sometimes not. You should have a look at http://developer.android.com/guide/practices/design/responsiveness.html for the ANR issue.

But in general you shouldn't start the waiting thread from the UI. The preferred solution is to use alarms for waiting tasks or services for background tasks.

A short example of an alarm can be found at: Android: How to use AlarmManager

Another possible solution is to start a background service which does all the initialisation of your app. After finishing the splash screen gets dismissed.

Upvotes: 2

Related Questions