[英]Thread : start, suspend, resume
我正在制作一個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;
}
}
然后,我需要獲取user&pass,然后再次使用該線程鎖定UI以檢查user&pass。問題是:我在暫停線程方面遇到問題:| 我的主要編程語言不是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();
}
}
...
}
有關等待和通知的更多信息: Java中使用wait()和notify()的簡單方案
最好在Thread
實現中引入boolean標志:
final private volatile boolean isSuspended = false;
然后,您可以將此標志設置為true
/ false
並在run
方法中重寫您的暫停邏輯,如下所示:
while (true) {
while (isSuspended) {
try {Thread.sleep(25);} catch (InterruptedException e) {}
}
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.