对于我的一个业余项目,我正在使用 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();
}
}
}
最佳答案
我不会使用 Thread.sleep(),我会使用计时器。
您可以设置时间,定时器会自动调用关联的任务。
在 Android 中,它的工作原理如下:
http://android.okhelp.cz/timer-simple-timertask-java-android-example/
我自己用过一次,但那是很久以前的事了。
顺便说一句:
您不必编写方法来检查 boolean 值。
这也有效:
boolean check = 5>3;
System.out.println("check: " + check);//"check true"
关于java - Android Java - 在随机时间范围内发送消息,每秒检查一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14112319/