2

对于我的一个副项目,我正在用 java 开发一个 android 应用程序。我不太了解java,但我正在尝试^^。

该项目是在一定范围内的随机时间有一个警报。问题是我的计时器和按钮冻结了,但一切仍然有效!有没有人可能对 thread.sleep 有另一种解决方案?

    public class MainActivity extends Activity {

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




    }
    public void StartChrono(View view) {
         final Chronometer chrono = (Chronometer)findViewById(R.id.chronometer1);
         chrono.setBase(SystemClock.elapsedRealtime());
         chrono.start();
         //Tick();
     }
     public int RandomTime(int min, int max)
     {
         int random = max - min;
         Random rand= new Random();
         random = rand.nextInt(random)+min;
         return random;
     }
     public boolean CheckUp(int randomtime,int chronotime)
     {
        boolean check = false;

        if(randomtime== chronotime)
         {
             check = true;
         }

        return check;
     }
     public void Tick()
     {
        boolean check = false;
        int randomtime = RandomTime(20,150);
        int time=1;

        do
         {  
            check = CheckUp(randomtime,time);
            time = time +1;
            try {
                Thread.sleep(1000);
                } 
            catch (InterruptedException e) {
                AlertDialog alertDialog;
                alertDialog = new AlertDialog.Builder(this).create();
                alertDialog.setTitle("Error - 000");
                alertDialog.setMessage("Could not check!");
                alertDialog.show();
            }

         }while(check == false);

        if(check == true)
        {
            AlertDialog alertDialog;
            alertDialog = new AlertDialog.Builder(this).create();
            alertDialog.setTitle("Yuy");
            alertDialog.setMessage("Switch!");
            alertDialog.show();
        }
     }
  }
4

2 回答 2

1

我不会使用 Thread.sleep(),我会使用 Timer。

您可以设置一个时间,定时器会自动调用相关的任务。

在 Android 中,它会像这样工作:

http://android.okhelp.cz/timer-simple-timertask-java-android-example/

我自己用过一次,但那是很久以前的事了。

顺便提一句。:

您不必编写方法来检查布尔值。

这也有效:

boolean  check = 5>3;
System.out.println("check: " + check);//"check true"
于 2013-01-01T17:17:37.073 回答
1

我肯定会为此任务使用处理程序:http: //developer.android.com/reference/android/os/Handler.html

一个基本的例子是这样的:

long timeDelay = 1000; // Set this to your random number.
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
     // Do whatever you need to do after a specified interval.  
    }
}, timeDelay);

在 onCreate 中实例化 Handler 并保留引用,以便您可以在方法中调用它。

只是为了澄清一下,为什么你不能使用 Thread.sleep() 来“休眠”特定的时间,是这样的:当你调用 Thread.sleep() 时,你会在 UI 线程上调用它,所以每个组件都在UI 线程(按钮、文本字段等)将在给定的时间内“休眠”,因此您基本上会停止整个应用程序。

另请参阅 Thread.sleep 的文档:

使发送此消息的线程在给定的时间间隔内休眠(以毫秒为单位)。

于 2013-01-01T17:39:21.960 回答