关于timertask的只执行一次的问题
我在安卓apk服务中设置了timer.schedule(task, 0, 3000);每三秒执行一次,但是却只执行一次;求助一下大佬;附上源码:
package com.example.liveon;
import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.icu.util.LocaleData;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.Toast;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class MyService extends Service {
final TimerTask task = new TimerTask() {
@Override
public void run() {
Log.d("toast", "toast");
timer.cancel();
}
};
final Timer timer = new Timer();
public MyService() {
Log.d("ccc","cccc");
timer.schedule(task, 0, 30);
new Thread(new Runnable() {
@Override
public void run() {
}
}).start();
final Handler handlerThree=new Handler(Looper.getMainLooper());
handlerThree.post(new Runnable(){
public void run(){
if (1>0) {
//timer.schedule(task, 0, 3000);
}
}
});
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
最终发现,在我的代码中,使用完timertask之后我把它关闭了,导致没办法继续执行任务;
关闭代码:timer.cancel();
页:
[1]