我在教程中制作了一个启动画面,它在Android 2.3+甚至在Android 4.0 +上运行良好但是如果我在我的Galaxy Tab上运行它( Android 3.1 )它是启动TWICE应用程序。 真的很讨厌我能在3.1上解决这个问题吗?
以下是代码:
public class SplashScreen extends Activity
{
protected boolean _active = true;
protected int _splashTime = 2000; // time to display the splash screen in ms
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
try{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
overridePendingTransition(0 , 0);
// thread for displaying the SplashScreen
Thread splashTread = new Thread() {
@Override
public void run() {
try {
int waited = 0;
while(_active && (waited < _splashTime)) {
sleep(100);
if(_active) {
waited += 100;
}
}
} catch(InterruptedException e) {
// do nothing
} finally {
// finish();
try{
Intent i = new Intent();
i.setClass(SplashScreen.this, MySecondActivity.class);
startActivity(i);
finish();
}
catch(Exception e)
{
ki(e);
}
}
}
};
splashTread.start();
}catch(Exception ex)
{
ki(ex);
}
}
@Override
public void onBackPressed() {
return;
}
//Toaster
public void ki(Exception message)
{
Toast myToast = Toast.makeText(getApplicationContext(), message.toString(), 1);
myToast.show();
}
}
因此,您看到它是一个简单的线程活动更改,但当它发生更改时,它会启动两次MySecondActivity。
到底是什么?
E D I T:
我刚刚意识到,只有在在横向模式下启动应用程序时才会出现此错误,而在启动/加载屏幕时。也许这是一个有价值的信息来解决这个问题。
答案 0 :(得分:2)
我认为你不应该使用睡眠。也许你可以试试这个。
private void popSplash() {
Message msg = splashHandler.obtainMessage();
splashHandler.sendMessageDelayed(msg, 2000);
}
private Handler splashHandler = new Handler() {
@Override
public void handleMessage(Message msg)
{
super.handleMessage(msg);
startActivity(new Intent(SplashScreen.this,MySecondActivity.class);;
finish();
}
};
只需在onCreate中调用popSplash。
这对我有用 -
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Display d = getWindowManager().getDefaultDisplay();
// For tablets, to avoid dublicate onCreates.
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
}
}
答案 1 :(得分:0)
public class SplashScreen extends Activity {
protected boolean _active = true;
protected int _splashTime = 5000;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
// thread for displaying the SplashScreen
Thread splashTread = new Thread() {
@Override
public void run() {
try {
int waited = 0;
while(_active && (waited < _splashTime)) {
sleep(100);
if(_active) {
waited += 100;
}
}
} catch(InterruptedException e) {
// do nothing
} finally {
finish();
Intent i = new Intent(SplashScreen.this, MyApp.class);
startActivity(i);
}
}
};
splashTread.start();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
_active = false;
}
return true;
}
}