我正在使用计时器来调用WebService,它将每隔5秒轮询我的代码
timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
new MyWS().execute(URL);
}
}, 1000, 5000);
但它在MyWS()上给了我FATAL异常.execute(URL);线。 以下显示log cat
05-30 11:46:47.299: E/AndroidRuntime(2801): FATAL EXCEPTION: Timer-0
05-30 11:46:47.299: E/AndroidRuntime(2801): java.lang.ExceptionInInitializerError
05-30 11:46:47.299: E/AndroidRuntime(2801): at com.example.vuzixvideo.MainActivity$1.run(MainActivity.java:59)
05-30 11:46:47.299: E/AndroidRuntime(2801): at java.util.Timer$TimerImpl.run(Timer.java:284)
05-30 11:46:47.299: E/AndroidRuntime(2801): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
05-30 11:46:47.299: E/AndroidRuntime(2801): at android.os.Handler.<init>(Handler.java:121)
05-30 11:46:47.299: E/AndroidRuntime(2801): at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:607)
05-30 11:46:47.299: E/AndroidRuntime(2801): at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:607)
05-30 11:46:47.299: E/AndroidRuntime(2801): at android.os.AsyncTask.<clinit>(AsyncTask.java:190)
答案 0 :(得分:0)
您在计时器中执行的操作必须尝试执行需要在主UI线程上执行的操作。试试这个:
timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
new MyWS().execute(URL);
}
});
}
}, 1000, 5000);
或者这个:
private Timer mTimer1;
private TimerTask mTt1;
private Handler mTimerHandler = new Handler(Looper.getMainLooper());
private void stopTimer(){
if(mTimer1 != null){
mTimer1.cancel();
mTimer1.purge();
}
}
private void startTimer(){
mTimer1 = new Timer();
mTt1 = new TimerTask() {
public void run() {
mTimerHandler.post(new Runnable() {
public void run(){
new MyWS().execute(URL);
}
});
}
};
mTimer1.schedule(mTt1, 1, 5000);
}
这会在主循环器上创建一个处理程序,计时器会向其发布操作。我没有测试它,但它应该工作。