我正在制作一个 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)
最佳答案
您可以尝试添加字段:
// 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
关于java - 线程 : start, 挂起、恢复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20763460/