编程语言
首页 > 编程语言> > java – Android加载时显示Splash-Screen

java – Android加载时显示Splash-Screen

作者:互联网

我有一个Android应用程序,显示3秒的“启动画面”.之后,MainActivity被加载.

不幸的是,MainActivity需要额外的约4秒才能加载.在第一次启动时甚至更长.但是,当应用程序加载时,一切运行顺利.

现在,如何在Splash Screen的显示期间实现MainActivity的加载?它应该显示一个图像,直到整个东西完全加载.
我已经阅读了有关Async-Task的内容,但我不知道该放在哪里以及如何正确使用它.有人能帮助我吗?

SplashScreen.java

public class SplashScreen extends Activity {
    private static int SPLASH_TIME_OUT = 3000;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_startup);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Intent i = new Intent(SplashScreen.this, MainActivity.class);
                startActivity(i);
                finish();
            }
        }, SPLASH_TIME_OUT);
    }
}

MainActivity.java

public class MainActivity extends Activity implements OnClickListener, MediaController.MediaPlayerControl {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Some heavy processing
        //starting services
        //starting Google Text to Speech
        //and so on...

    }

}

解决方法:

如果没有关于应该显示启动屏幕的时间的特定限制,您可以通过以下方式使用AsyncTask:

public class SplashScreen extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_startup);
        startHeavyProcessing();

    }

    private void startHeavyProcessing(){
       new LongOperation().execute("");
    }

    private class LongOperation extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            //some heavy processing resulting in a Data String
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    Thread.interrupted();
                }
            }
            return "whatever result you have";
        }

        @Override
        protected void onPostExecute(String result) {
            Intent i = new Intent(SplashScreen.this, MainActivity.class);
            i.putExtra("data", result);
            startActivity(i);
            finish();
        }

        @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(Void... values) {}
    }
}

如果结果数据的性质不是String,那么您可以将Parcelable Object作为额外的活动.在onCreate中,您可以使用以下方法检索数据:

.getIntent()getExtras.getString( ‘数据’);

标签:android,java,splash-screen
来源: https://codeday.me/bug/20190926/1821500.html