0

編集:問題が見つかりました。それは Thread.Sleep です。アプリケーションを少し待機させる他の方法はありますか?

Android開発を学ぼうとしているので、Androidスタジオを使用しています。メインのアクティビティではないアクティビティがあり、アクティビティの開始時に 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);
}

}
4

2 に答える 2

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);
于 2014-04-12T14:13:04.257 に答える