[英]Timer() function not working when going to another activity
In my application i want to close it after 5 seconds using Timer() function.It works when i am in MainActivity but when i go to another activity then the application do not close.Now how to run this Timer() function in background if i switch activity.What to do in this case? 在我的应用程序中,我想使用Timer()函数在5秒钟后关闭它。当我处于MainActivity时它可以工作,但是当我进行其他活动时,该应用程序无法关闭。现在如何在后台运行此Timer()函数我切换活动。在这种情况下该怎么办?
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
finish();
}
}, 5000); // Application will be closed after 5 seconds
You achieve this using broadcast receiver. 您可以使用广播接收器来实现。 in your activity which you want to finish you need to create broadcast receiver.
在您要完成的活动中,需要创建广播接收器。
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();
}
};
}
now in your second activity you need to send broadcast after 5 second eg 现在在第二个活动中,您需要在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);
}
}
or other possible way is directly use postDelayed()
method in your test activity eg 或其他可能的方法是在测试活动中直接使用
postDelayed()
方法,例如
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
finish();
}
}, 5000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.