[android] 在AsyncTask中使用等待


Answers

您可以使用Thread.sleep方法

    try {
        Thread.sleep(1000);         
    } catch (InterruptedException e) {
       e.printStackTrace();
    }
Question

AsyncTask使用wait時,我得到ERROR/AndroidRuntime(24230): Caused by: java.lang.IllegalMonitorStateException: object not locked by thread before wait()

是否可以使用Asynctask來等待? 怎麼樣?

謝謝

class WaitSplash extends AsyncTask<Void, Void, Void> {
    protected Void doInBackground(Void... params) {
        try {
            wait(MIN_SPLASH_DURATION);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }       

    protected void onPostExecute() {
        waitSplashFinished = true;
        finished();
    }
}  



你有這樣的方式與asyntask和wait();

public class yourAsynctask extends AsyncTask<Void, Void, Void> {
    public boolean inWait;
    public boolean stopWork; 

    @Override
    protected void onPreExecute() {
        inWait = false;
        stopWork = false;
    }

    @Override
    protected Void doInBackground(Void... params) {
        synchronized (this) {
            while(true) {
                if(stopWork) return null;
                if(youHaveWork) {
                    //make some
                } else {
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }

    public void mynotify() {
        synchronized (this) {
            if(inWait) {
                notify();
                inWait = false;
            }
        }
    }

    public void setStopWork() {
        synchronized (this) {
            stopWork = false;
            if(inWait) {
                notify();
                inWait = false;
            }
        }
    }
}



如果你只是推遲一個方法的執行時間,一個好的選擇是Handler.postDelayed()

定義處理程序和可運行...

private Handler handler = new Handler();
private Runnable runnable = new Runnable() {        
    finished();
};

並延遲執行...

handler.postDelayed(runnable, MIN_SPLASH_DURATION);





Links