我尝试覆盖 onBackPressed 以不仅完成当前活动,而且在我调用下一个活动的意图时中断线程。当我之前按下时,启动活动完成,但线程继续运行并将意图调用到下一个活动。现在我已经在BackPressed 上包含了线程中断,当我按下返回时应用程序崩溃了。我究竟做错了什么?
skipscreen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SharedPreferences savestate = getSharedPreferences("skip", MODE_PRIVATE);
savestate.edit().putBoolean("skip", true).apply();
skip= true;
homeintent();
}
});
Thread splashthread = new Thread() {
@Override
public void run() {
try {
sleep(3000);
if (!skip) { homeintent();}
} catch (InterruptedException Interrupt) {
Interrupt.printStackTrace();
}
}
};
splashthread.start();
}
private void homeintent() {
Intent i = new Intent(splash.this, home.class);
startActivity(i);
finish();
}
@Override
public void onBackPressed() {
splashthread.interrupt();
finish();
}
}
更新:(这个解决方案对我有用)。
skipscreen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SharedPreferences savestate = getSharedPreferences("skip", MODE_PRIVATE);
savestate.edit().putBoolean("skip", true).apply();
skip= true;
homeintent();
}
});
Thread splashthread = new Thread() {
@Override
public void run() {
try {
sleep(3000);
if (!skip) { homeintent();}
} catch (InterruptedException Interrupt) {
Interrupt.printStackTrace();
}
}
};
splashthread.start();
}
private void homeintent() {
if (!ThreadInterrupted) {
Intent i = new Intent(splash.this, home.class);
startActivity(i);
}
finish();
}
@Override
public void onBackPressed() {
SharedPreferences savestate= getSharedPreferences("ThreadInterrupted", MODE_PRIVATE);
savestate.edit().putBoolean("ThreadInterrupted", true).apply();
ThreadInterrupted = true;
homeintent();
}
}