所以我有一个线程,如果拖动几乎在draggingzone之外,它每10ms检查一次。基本上我的线程代码99%的时间都没有做任何事情所以我应该让它暂停并仅在需要时恢复?或者,当左右都是假的时,这实际上什么都不做?
我的代码看起来像这样
<style name="MyDrawerArrowToggle" parent="Widget.AppCompat.DrawerArrowToggle">
<item name="color">@color/white</item>
</style>
答案 0 :(得分:1)
看起来没有必要在这里使用Thread,你应该切换到使用Handler和postDelayed()
首先,将Handler,boolean和Runnable声明为实例变量:
Handler handler;
boolean b;
Runnable checkDragZone = new Runnable(){
@Override
public void run() {
if (right) {
dragzone.moveleft(-5);
} else if (left) {
dragzone.moveleft(5);
}
if (b){
handler.postDelayed(this, 10);
}
}
};
要开始监控,请将b
设置为true,然后启动Runnable:
handler = new Handler();
b = true;
handler.postDelayed(checkDragZone, 10);
要暂停(暂时或永久),只需将b
设为false:
b = false;
答案 1 :(得分:0)
让它保持运行并不是一个好习惯。您可以在检测到拖动操作时启动它,然后在完成后将其释放。
答案 2 :(得分:0)
Runnable runnable;
Thread globalThread;
public void startThread() {
if (threadController) {
runnable = new Runnable() {
@Override
public void run() {
while (threadController) {
for (int i = 0; i < adapter.getCount(); i++) {
final int value = i;
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
@Override
public void run() {
viewPager.setCurrentItem(value, true);
}
});
}
}
}
};
globalThread = new Thread(runnable);
globalThread.start();
} else {
return;
}
}
@Override
public void onPause() {
super.onPause();
threadController = false;
handler.removeCallbacks(runnable);
runnable = null;
if (globalThread != null) {
globalThread.interrupt();
}
}
@Override
public void onDestroy() {
super.onDestroy();
threadController = false;
}
您的决心必须像globalThread.interrupt();