[英]Timer() function not working when going to another activity
在我的應用程序中,我想使用Timer()函數在5秒鍾后關閉它。當我處於MainActivity時它可以工作,但是當我進行其他活動時,該應用程序無法關閉。現在如何在后台運行此Timer()函數我切換活動。在這種情況下該怎么辦?
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
finish();
}
}, 5000); // Application will be closed after 5 seconds
您可以使用廣播接收器來實現。 在您要完成的活動中,需要創建廣播接收器。
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();
}
};
}
現在在第二個活動中,您需要在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);
}
}
或其他可能的方法是在測試活動中直接使用postDelayed()
方法,例如
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
finish();
}
}, 5000);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.