我在 TimerTask 干扰应用内购买(异步任务)时遇到问题。 我对线程很弱,所以我相信它在主 UI 线程上运行,占用资源。 我如何在 UI 线程之外运行它?我已经搜索并尝试了一些使用处理程序的建议。但似乎我得到了相同的结果,应用程序变得非常滞后。 当我不运行此任务(每 500 毫秒刷新一次)时, Activity 运行平稳,并且在应用内购买期间没有挂起。 感谢您的帮助,代码 fragment 如下:
公共(public)类 DummyButtonClickerActivity 扩展 Activity {
protected Timer timeTicker = new Timer("Ticker");
private Handler timerHandler = new Handler();
protected int timeTickDown = 20;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainhd);
// start money earned timer handler
TimerTask tick = new TimerTask() {
public void run() {
myTickTask();
}
};
timeTicker.scheduleAtFixedRate(tick, 0, 500); // 500 ms each
} // End OnCreate
protected void myTickTask() {
if (timeTickDown == 0) {
/// run my code here
//total = total + _Rate;
timerHandler.post(doUpdateTimeout);
}
else if(timeTickDown < 0) {
// do nothing
}
timeTickDown--;
}
private Runnable doUpdateTimeout = new Runnable() {
public void run() {
updateTimeout();
}
};
private void updateTimeout() {
// reset tick
timeTickDown = 2; // 2* 500ms == once a second
}
最佳答案
您可以使用 HandlerThread
来在单独的线程上运行您的处理程序
文档:
Handy class for starting a new thread that has a looper.
The looper can then be used to create handler classes. Note that start() must still be called.
示例:
HandlerThread mHandlerThread = new HandlerThread("my-handler");
mHandlerThread.start();
Handler mHandler = new Handler(mHandlerThread.getLooper());
更新:
private Runnable doUpdateTimeout;
private HandlerThread mHandlerThread;
private Handler timerHandler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainhd);
// start money earned timer handler
TimerTask tick = new TimerTask() {
public void run() {
myTickTask();
}
};
mHandlerThread = new HandlerThread("my-handler");
mHandlerThread.start();
timerHandler = new Handler(mHandlerThread.getLooper());
doUpdateTimeout = new Runnable() {
public void run() {
updateTimeout();
}
};
timeTicker.scheduleAtFixedRate(tick, 0, 500); // 500 ms each
} // End OnCreate
protected void myTickTask() {
if (timeTickDown == 0) {
/// run my code here
//total = total + _Rate;
timerHandler.post(doUpdateTimeout);
}
else if(timeTickDown < 0) {
// do nothing
}
timeTickDown--;
}
private void updateTimeout() {
// reset tick
timeTickDown = 2; // 2* 500ms == once a second
}
}
当你想从不同的线程更新 TextView 时
调用这个:
YOU_ACITIVITY_CLASS.this.runOnUiThread(new Runnable() {
@Override
public void run() {
//update here
}
});
关于java - 如何在主 UI 线程之外运行 TimerTask?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24197177/