[英]Splash screen issue
我正在使用以下代码创建启动画面,当我按下返回键时,应用程序将移动到主屏幕并在几秒钟内显示我的下一个主菜单屏幕。我在 onBackPressed() 中调用 finish(),我想关闭在启动画面中按返回键的应用程序。任何人都可以帮助我吗?
谢谢!!
Thread splashThread = new Thread() {
@Override
public void run() {
try {
int waited = 0;
while (_active && (waited < 2000)) {
sleep(100);
if(_active) {
waited += 100;
}
}
} catch (InterruptedException e) {
// do nothing
} finally {
finish();
startActivity(new Intent("next activity"));
stop();
}
}
};
splashThread.start();
这是因为你调用finish();
在startActivity(new Intent("next activity"));
交换finish();
与startActivity(new Intent("next activity"));
尝试使用这个:
SplashScreen.this.finish();
其中 SplashScreen 是 Activity 的名称。
它在我的应用程序中工作
public class Splash extends Activity {
protected boolean _active = true;
protected int _splashTime = 3000;
Thread splashTread;
private boolean stop = false;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
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 {
if(!stop){
startActivity(new Intent(Splash.this,Home.class));
finish();
}
else
finish();
}
}
};
splashTread.start();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
if(splashTread.isAlive())
this.stop = true;
}
return true;
}
}
此解决方案仅解决后退按钮的问题。 如果用户按下主页按钮,仍然会发生不需要的行为。 覆盖 onStop 方法并在那里做你的事情不是更容易吗?
@Override
public void onStop(){
super.onStop();
if(splashTread.isAlive())
this.stop = true;
}
public class SplashActivity extends Activity {
Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
handler=new Handler();
handler.postDelayed(() -> {
Intent intent=new Intent(SplashActivity.this, Home.class);
startActivity(intent);
finish();
},3000);
}
}
AndriodManifest.xml
<activity
android:name=".SplashActivity"
android:theme="@style/AppTheme"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.