简体   繁体   中英

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 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

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

new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            finish();

        }
    }, 5000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM