我的onStart代码有什么问题?

时间:2014-04-12 13:42:24

标签: android android-studio onstart

编辑:我发现了问题,它是Thread.Sleep有没有其他方法让我的应用程序等一下?

我正在尝试学习android开发,所以我正在使用android studio。 我有一个活动,这不是主要的活动,我试图建立一个计时器,从活动开始时的40分钟开始计数,但出于某种原因,我按下主活动中的按钮,应该更改活动应用程序崩溃到计时器的那个。 这是计时器的活动代码:

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;


public class Timer extends Activity {

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

}

@Override
protected void onStart() {
        String counter;
        int totalSeconds = 2400;
        int minLeft, secLeft;
        for (int i = totalSeconds; i > 0; i--)
        {
            try
            {
                Thread.sleep(1000L);
            }
            catch (InterruptedException e) {e.printStackTrace();}
            minLeft=(int)Math.floor(i/60);
            secLeft=i-(minLeft*60);
            counter = minLeft+":"+secLeft;
            TextView tv = (TextView)findViewById(R.id.timer);
            tv.setText(counter);
        }
    }

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.quiz, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

2 个答案:

答案 0 :(得分:1)

您需要将所有计数器逻辑移出主线程。尝试这样的事情:

private int secondsLeft = 2400;

private Handler mHandler = new Handler();

public void onStart() {
    super.onStart();

    final TextView tv = (TextView)findViewById(R.id.timer);

    mHandler.postDelayed(new Runnable() {

        public void run() {
            secondsLeft--;
            int minLeft = (int)Math.floor(secondsLeft / 60);
            int secLeft = secondsLeft - (minLeft * 60);
            tv.setText(minLeft + ":" + secLeft);

            if (secondsLeft > 0)
                mHandler.postDelayed(this, 1000);
        }

    }, 1000);

答案 1 :(得分:0)

您可能错过了在被覆盖的super.onStart()

中致电onStart()