在我的应用程序中,我想使用 Timer() 函数在 5 秒后关闭它。当我在 MainActivity 中时它可以工作,但是当我转到另一个 Activity 时应用程序不会关闭。现在如何运行这个 Timer() 函数如果我切换 Activity ,则会在后台运行。在这种情况下该怎么办?
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
finish();
}
}, 5000); // Application will be closed after 5 seconds
最佳答案
您可以使用广播接收器来实现这一点。在您想要完成的 Activity 中,您需要创建广播接收器。
public class TestActivity extends Activity {
public static String intent_filter_finish = "com.test.finish";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
registerReceiver(finishReceiver,
new IntentFilter(intent_filter_finish));
}
@Override
protected void onDestroy() {
unregisterReceiver(finishReceiver);
super.onDestroy();
}
BroadcastReceiver finishReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
}
现在,在您的第二个 Activity 中,您需要在 5 秒后发送广播,例如
public class SecondActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
sendBroadcast(new Intent(TestActivity.intent_filter_finish));
}
}, 5000);
}
}
或其他可能的方式是直接在测试 Activity 中使用 postDelayed()
方法,例如
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
finish();
}
}, 5000);
关于java - 转到另一个 Activity 时 Timer() 函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36213815/