我正在制作Android应用(最小SDK:8,目标SDK:19)
现在我想在开始时设置一个加载图标,直到应用程序检查互联网中心性
直到现在我没有问题
我有这个方法为我做:
void setLoader(boolean T, String msg){
View LAY = findViewById(R.id.loaderLayout);
TextView MTV = (TextView) findViewById(R.id.loader_msg);
if(T && !loaderStarted){
loader.start();
LAY.setVisibility(View.VISIBLE);
MTV.setText(msg);
loaderStarted = true;
}
else if (!T && loaderStarted) {
loader.interrupt();
LAY.setVisibility(View.GONE);
loaderStarted = false;
}
}
然后我需要获得用户和传递,然后再次使用该线程锁定UI以检查用户和传递 问题是 : 我有问题暂停一个线程:| 我的主要编程语言不是java
所以请帮助我,我有这样的线程:
//first make loading icon visible then call :
final private Thread loader = new Thread(new Runnable(){
@Override
public void run() {
int i = 0;
while (true){
if(loader.isInterrupted()){
return;
}
try {Thread.sleep(25);} catch (InterruptedException e) {}
final int j = i;
runOnUiThread(new Runnable(){
public void run() {
ImageView imageView = (ImageView) findViewById(R.id.loaderImage);
Matrix matrix = new Matrix();
imageView.setScaleType(ScaleType.MATRIX);
int newWIDTH = imageView.getWidth();
int newHIEGHT = imageView.getHeight();
matrix.postScale(((float)(newWIDTH))/imageView.getDrawable().getBounds().width(), ((float)(newHIEGHT))/imageView.getDrawable().getBounds().height());
matrix.postRotate((float) j, newWIDTH/2, newHIEGHT/2);
imageView.setImageMatrix(matrix);
}
});
i = (i + 15) % 360;
}
}
});
然后我需要一个像这样的方法:
void setLoader(boolean T, String msg){
View LAY = findViewById(R.id.loaderLayout);
TextView MTV = (TextView) findViewById(R.id.loader_msg);
if(T && !loaderStarted){
loader.start();
LAY.setVisibility(View.VISIBLE);
MTV.setText(msg);
loaderStarted = true;
}
else if(T && loaderSuspended && loaderStarted){
loader.resume();
LAY.setVisibility(View.VISIBLE);
MTV.setText(msg);
loaderSuspended = false;
}
else if (loaderStarted && !loaderSuspended) {
loader.suspend();
LAY.setVisibility(View.GONE);
loaderStarted = false;
loaderSuspended = true;
}
}
暂停线程然后恢复它 (.suspend()和.resume()已弃用)
提前致谢:) 抱歉可怕的英语(:D)
答案 0 :(得分:1)
您可以尝试添加字段:
// defines the paused state
private volatile boolean isPaused = false;
// a monitor object for wait/notify pattern
private final Object suspender = new Object();
然后在你的逻辑中:
void pause(){
synchronized(suspender){
isPaused = true;
}
}
void resume(){
synchronized(suspender){
isPaused = false;
suspender.notify();
}
}
while (true){
if(loader.isInterrupted()){
return;
}
// this outside loop is needed to deal with spurious wakeup
synchronized (suspender){
while(isPaused){
suspender.wait();
}
}
...
}
有关等待和通知的更多信息:A simple scenario using wait() and notify() in java
答案 1 :(得分:0)
最好在Thread
实现中引入布尔标志:
final private volatile boolean isSuspended = false;
然后您可以将此标记设置为true
/ false
,并在run
方法中重写暂停逻辑,如下所示:
while (true) {
while (isSuspended) {
try {Thread.sleep(25);} catch (InterruptedException e) {}
}
...
}