如何在Android Studio中创建计时任务OUTSIDE onCreate?

时间:2015-10-08 02:40:18

标签: android timer

所以我有一个非常愚蠢的问题。我能够创建一个简单的计时器任务,每秒都会滴答作响:

final Timer timer = new Timer();

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (counter == 0) {
                            //Reload Map...
                            timer.cancel();
                            Intent intent = new Intent(MapsActivity.this, MapsActivity.class);
                            startActivity(intent);
                        } else {
                            TimeLabel.setText(Integer.toString(counter));
                            counter = counter - 1;
                        }
                    }
                });

            }
        }, 0, 1000);

一分钟后,它会重新加载我的谷歌地图。但是当我尝试打开其他活动并尝试返回Map时,我的MapsActivity并未被杀死(即使我使用了finish();)。这就是我的计时器重叠的原因。

我猜我应该创建计时器OUTSIDE onCreate,但这样做没有成功。你能帮帮我们吗?

1 个答案:

答案 0 :(得分:0)

试试这个

public class MainActivity extends Activity {

    //Global Variables
    Timer timer;
    TimerTask task;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Make a method to make it cleaner
        setTimer();
    }

    private void setTimer() {
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (counter == 0) {
                            //Reload Map...
                            timer.cancel();
                            Intent intent = new Intent(MapsActivity.this, MapsActivity.class);
                            startActivity(intent);
                        } else {
                            TimeLabel.setText(Integer.toString(counter));
                            counter = counter - 1;
                        }
                    }
                });

            }
        };

    }

    @Override
    protected void onResume() {
        super.onResume();

        //This will be called after onCreate or your activity is resumed
        timer.schedule(task, 0, 1000);
    }

    @Override
    protected void onPause() {
        super.onPause();

        //This will be called if the app is sent to background or the phone is locked
        //Also this prevent you from duplicating the instance of your timer
        timer.cancel();
    }
}