我正在制作一个应用程序,它每隔一段时间从网站读取数据并将值发布到屏幕上。我很难让它开始和停止它。
我可以让循环开始没有问题,我也可以停止它。但是如果我尝试重新启动它,程序就会崩溃。
代码在这里:
final Timer myTimer = new Timer();
loop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
MyTimerTask mytimertask = new MyTimerTask();
myTimer.scheduleAtFixedRate(mytimertask, 0, 5000);
}
});
stoploop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText("STOPPED");
myTimer.cancel();
}
});
}
private class MyTimerTask extends TimerTask {
@Override
public void run() {
// TODO Auto-generated method stub
runOnUiThread(new Runnable(){
public void run() {
// TODO Auto-generated method stub
//textView.setText("changed");
readWebpage(text);
}
});
}
}
我对线程很陌生,这就是为什么我可能在这里遗漏了一些基本的东西。任何帮助将不胜感激。
谢谢
[编辑]我应该补充一下,我从这里的一个解决方案中改编了这个: 如何在按下按钮后每 10 分钟重复一次方法并在另一个按钮按下时结束它
06-29 01:38:02.958: D/AndroidRuntime(1119): Shutting down VM
06-29 01:38:02.958: W/dalvikvm(1119): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
06-29 01:38:02.968: E/AndroidRuntime(1119): FATAL EXCEPTION: main
06-29 01:38:02.968: E/AndroidRuntime(1119): java.lang.IllegalStateException: Timer was canceled
06-29 01:38:02.968: E/AndroidRuntime(1119): at java.util.Timer.scheduleImpl(Timer.java:561)
06-29 01:38:02.968: E/AndroidRuntime(1119): at java.util.Timer.scheduleAtFixedRate(Timer.java:528)
06-29 01:38:02.968: E/AndroidRuntime(1119): at com.example.beam.MainActivity$1.onClick(MainActivity.java:67)
06-29 01:38:02.968: E/AndroidRuntime(1119): at android.view.View.performClick(View.java:4084)
06-29 01:38:02.968: E/AndroidRuntime(1119): at android.view.View$PerformClick.run(View.java:16966)
06-29 01:38:02.968: E/AndroidRuntime(1119): at android.os.Handler.handleCallback(Handler.java:615)
06-29 01:38:02.968: E/AndroidRuntime(1119): at android.os.Handler.dispatchMessage(Handler.java:92)
06-29 01:38:02.968: E/AndroidRuntime(1119): at android.os.Looper.loop(Looper.java:137)
06-29 01:38:02.968: E/AndroidRuntime(1119): at android.app.ActivityThread.main(ActivityThread.java:4745)
06-29 01:38:02.968: E/AndroidRuntime(1119): at java.lang.reflect.Method.invokeNative(Native Method)
06-29 01:38:02.968: E/AndroidRuntime(1119): at java.lang.reflect.Method.invoke(Method.java:511)
06-29 01:38:02.968: E/AndroidRuntime(1119): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
06-29 01:38:02.968: E/AndroidRuntime(1119): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
06-29 01:38:02.968: E/AndroidRuntime(1119): at dalvik.system.NativeStart.main(Native Method)
06-29 01:38:03.028: W/ActivityManager(156): Force finishing activity com.example.beam/.MainActivity
06-29 01:38:03.039: W/WindowManager(156): Failure taking screenshot for (246x410) to layer 21010
06-29 01:38:03.552: W/ActivityManager(156): Activity pause timeout for ActivityRecord{41366318 com.example.beam/.MainActivity}