Timer mTimer;
void scheduleSyncIn(int aSeconds){
if (mTimer != null) {
mTimer.cancel();
mTimer = null;
}
mTimer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
handleTimeout();
}
};
if (request) {
mTimer.schedule(task, aSeconds * 1000);
}
}
由计时器任务调用的方法
void handleTimeout(){
Handler mainHandler = new Handler(mContext.getMainLooper());
Runnable runnable = new Runnable(){
@Override
public void run() {
sync(); //call the sync
}
};
mainHandler.post(runnable);
}
从这里我从Play商店得到以下报告
java.lang.OutOfMemoryError: pthread_create (stack size 16384 bytes) failed: Try again
at java.lang.VMThread.create(Native Method)
at java.lang.Thread.start(Thread.java:1029)
at java.util.Timer$TimerImpl.<init>(Timer.java:192)
at java.util.Timer.<init>(Timer.java:367)
at java.util.Timer.<init>(Timer.java:387)
at java.util.Timer.<init>(Timer.java:394)
at com.example.Manager.scheduleSyncIn(Manager.java:66)
at com.example.Manager.scheduleSync(Manager.java:56)
at com.example.Manager.RequestDone(Manager.java:180)
com.example.Manager.Remote$GetMetaData.onPostExecute(Remote.java:338)
at com.example.Manager.Remote$GetMetaData.onPostExecute(Remote.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5137)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:611)
at dalvik.system.NativeStart.main(Native Method)
现在我不知道为什么这个错误在我取消计时器并且每次在初始化之前将它释放给GC。 谢谢你的帮助。
答案 0 :(得分:3)
我建议在Android中使用Handler
代替Timer
,它可能会导致您的应用中出现memory leaks。
<强>样品:强>
Handler mHandler;
Runnable mRunnable;
void scheduleSyncIn(int aSeconds){
mHandler = new Handler();
mRunnable = new Runnable() {
@Override
public void run() {
mHandler.postDelayed(mRunnable, aSeconds);
}
};
mHandler.postDelayed(mRunnable, aSeconds);
}