我有一个Android应用程序,它显示了一个" Splash Screen"持续3秒之后,MainActivity被加载。
不幸的是,MainActivity需要额外的~4秒才能加载。在第一次启动时甚至更长。但是,当加载App时,一切都顺利进行。
我正在使用Async-Task,但是没有获得所需的结果,有时app会崩溃。有人能帮帮我吗?
SplashScreen.java
公共类SplashScreen扩展了AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
new Fetchdata().execute();
}
私有类Fetchdata扩展了AsyncTask {
@Override
protected Void doInBackground(Void... voids) {
Intent intent = new Intent(SplashScreen.this,FetchApiService.class);
startService(intent);
for (int i = 0; i < 3; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.interrupted();
}
}
return null;
}
@Override
protected void onPostExecute(Void result){
Intent i = new Intent(SplashScreen.this, MainActivity.class);
startActivity(i);
finish();
}
}
@Override
public void onDestroy(){
super.onDestroy();
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Some heavy processing
//starting services
Intent intent = new Intent(this,FetchApiService.class);
startService(intent);
}
}