How to start an activity upon the completion of a

2019-07-24 08:00发布

问题:

I'm trying to start a new activity "SMS.java", if I dont respond to my timer within 30secs. After 30secs, the new ativity should be started. Can anyone help me out??? The class Timer on line 5 extends a CountDownTimer.. Here's the code:

//TimerAct.java
public class TimerAct extends Activity
{
    static TextView timeDisplay;
    Timer t;
    int length = 30000;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.time);

        timeDisplay = (TextView) findViewById(R.id.timer);
        timeDisplay.setText("Time left: " + length / 1000);
        t = new Timer(length, 1000);
        t.start();
        View b1 = findViewById(R.id.abort);
        b1.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                t.cancel();
                finish();
            }
        });
    }   
}

//Timer.java
public class Timer extends CountDownTimer
{
    public Timer(long millisInFuture, long countDownInterval)
    {
        super(millisInFuture, countDownInterval);
    }

    public void onTick(long millisUntilFinished)
    {
        TimerAct.timeDisplay.setText("Time left: " + millisUntilFinished / 1000);
    }

    public void onFinish()
    {
        TimerAct.timeDisplay.setText("Time over!!!");
    }
}

回答1:

For a timer method, better you can use with threading. It will work. This is the example for Show Timer in android using threads. It runs the thread every second. Change the time if you want.

Timer MyTimer=new Timer();
        MyTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    public void run() {
                        TimerBtn=(Button) findViewById(R.id.Timer);
                        TimerBtn.setText(new Date().toString());
                }
                });
            }
            }, 0, 1000);


回答2:

What I do is call a method from the Activity on my CountDownTimer class, like this:

//Timer Class inside my Activity
    public class Splash extends CountDownTimer{

        public Splash(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            nextActivity(Login.class, true);
        }

        @Override
        public void onTick(long millisUntilFinished) {}
    }

//Method on my Activity Class

    protected void nextActivity(Class<?> myClass, boolean finish) {
        Intent myIntent = new Intent(this, myClass);
        myIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        startActivity(myIntent);

        if(finish)
            finish();
    }