对于我的侧面项目,我正在开发一个带有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();
}
}
}
答案 0 :(得分: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"
答案 1 :(得分: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线程上运行的每个组件(按钮,文本字段等)都会“睡眠”#34;在给定的时间内,你基本上会停止整个申请。
另请参阅Thread.sleep的文档:
使发送此消息的线程休眠给定的 时间间隔(以毫秒为单位)。