在AsyncTask中使用等待
在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(); } }
使用Thread.sleep()而不是wait()
。
您可以使用Thread.sleep方法
try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
@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; }
如果你只是推迟一个方法的执行时间,一个好的select是Handler.postDelayed()
定义处理程序和可运行…
private Handler handler = new Handler(); private Runnable runnable = new Runnable() { finished(); };
并延迟执行…
handler.postDelayed(runnable, MIN_SPLASH_DURATION);
为此使用线程
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; }
在触摸事件,线程得到通知..可以根据您的需要改变。
你有这样的方式与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; } } } }