Reputation: 51
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 timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
finish();
}
}, 5000); // Application will be closed after 5 seconds
Upvotes: 2
Views: 403
Reputation: 1510
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 e.g.
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 e.g.
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
finish();
}
}, 5000);
Upvotes: 3