在wait
中使用AsyncTask
时,我得到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();
}
}
答案 0 :(得分:92)
使用Thread.sleep()代替wait()
。
答案 1 :(得分:26)
您可以使用Thread.sleep方法
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
答案 2 :(得分:7)
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
Thread.currentThread();
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
答案 3 :(得分:3)
如果您希望在一段时间内推迟执行某个方法,那么一个不错的选择就是Handler.postDelayed()
定义处理程序和runnable ......
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
finished();
};
并以延迟执行......
handler.postDelayed(runnable, MIN_SPLASH_DURATION);
答案 4 :(得分:1)
使用线程
public class SplashActivity extends Activity{
int splashTime = 5000;
private Thread splashThread;
private Context mContext;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.mContext = this;
setContentView(R.layout.splash_layout);
splashThread = new Thread(){
public void run() {
try{
synchronized (this) {
wait(splashTime);
}
}catch(InterruptedException ex){
ex.printStackTrace();
}finally{
Intent i = new Intent(mContext,LocationDemo.class);
startActivity(i);
stop();
}
}
};
splashThread.start();
}
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
synchronized (splashThread) {
splashThread.notifyAll();
}
}
return true;
}
触摸事件,线程得到通知..可以根据您的需要进行更改。
答案 5 :(得分:0)
您可以通过这种方式使用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;
}
}
}
}