我有一个Android应用程序,它运作良好,但就在最近它开始显示一个问题。
问题是它正常启动,但当我点击它时会创建一个新的主要活动,当我再次点击它时,应用程序正确关闭。
这里有一段视频:https://streamable.com/s/s7m8c/snygay?muted=1
我不能自己解决这个问题,所以有谁知道它为什么会发生?
编辑: 该活动是使用此代码启动的。
mHandler = new Handler();
mActivityLaunchRunnable = new Runnable() {
@Override
public void run() {
// This method will be executed once the timer is over
// Start app main activity
Intent i = new Intent(SplashScreen.this, MainActivity.class);
startActivity(i);
// close this activity
finish();
}
};
mHandler.postDelayed(mActivityLaunchRunnable, SPLASH_TIME_OUT);
initialTime = System.currentTimeMillis();
并且未覆盖onBackPressed
答案 0 :(得分:0)
这不是创建启动画面的正确方法!
这就是我通常实现它的方式 -
ImageView splashImg = (ImageView)(findViewById(R.id.splash_img));
ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(splashImg,"alpha",0,1);
objectAnimator.setDuration(2000);
objectAnimator.setInterpolator(new AccelerateInterpolator(3f));
objectAnimator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animator) {
Log.i(TAG,"on animation start");
}
@Override
public void onAnimationEnd(Animator animator) {
Log.i(TAG,"on animation end");
startActivity(new Intent(context, MainActivity.class));
}
@Override
public void onAnimationCancel(Animator animator) {
Log.i(TAG,"on animation cancel");
}
@Override
public void onAnimationRepeat(Animator animator) {
Log.i(TAG,"on animation repeat");
}
});
objectAnimator.start();
在MainActivity中,将onBackPressed()重写为 -
@Override
public void onBackPressed() {
finishAffinity();
}
Here's a short tutorial on ObjectAnimator
希望这有帮助!
答案 1 :(得分:0)
您需要停止将启动画面活动添加到堆栈中。您可以在manifest
中执行此操作:
<activity
android:name=".SplashScreen"
android:noHistory="true" />
然后,您可以删除代码段中的finish()
。
注意:另一种方法是使用FLAG_ACTIVITY_NO_HISTORY
答案 2 :(得分:0)
mHandler = new Handler();
mActivityLaunchRunnable = new Runnable() {
@Override
public void run() {
// This method will be executed once the timer is over
// Start app main activity
Intent i = new Intent(SplashScreen.this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
// close this activity
finish();
}
};
mHandler.postDelayed(mActivityLaunchRunnable, SPLASH_TIME_OUT);
initialTime = System.currentTimeMillis();