Android Splash Screen causing ANR

喜夏-厌秋 提交于 2020-01-25 07:38:25

问题


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();

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/4414737/android-splash-screen-causing-anr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!