How to finish current activity in Android

前端 未结 8 1444
长发绾君心
长发绾君心 2020-11-28 03:19

I have an Android application. I am making a loading screen with a progress bar.

I entered a delay in the onCreate method. When the timer finishes, I want to finis

8条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 03:27

    You need to call finish() from the UI thread, not a background thread. The way to do this is to declare a Handler and ask the Handler to run a Runnable on the UI thread. For example:

    public class LoadingScreen extends Activity{
        private LoadingScreen loadingScreen;
        Intent i = new Intent(this, HomeScreen.class);
        Handler handler;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            handler = new Handler();
            setContentView(R.layout.loading);
    
            CountDownTimer timer = new CountDownTimer(10000, 1000) //10seceonds Timer
            {
                 @Override
                 public void onTick(long l) 
                 {
    
                 }
    
                 @Override
                 public void onFinish() 
                 {
                     handler.post(new Runnable() {
                         public void run() {
                             loadingScreen.finishActivity(0);
                             startActivity(i);
                         }
                     });
                 };
            }.start();
        }
    }
    

提交回复
热议问题