When using a wait
in an AsyncTask
, I get ERROR/AndroidRuntime(24230): Caused by: java.lang.IllegalMonitorStateException: object not locked by thr
Use threads for this
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;
}
on touch event, thread get notified.. can change according to your need.
If you're looking to just postpone execution of a method for a set amount of time, a good option is Handler.postDelayed()
define the handler and runnable...
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
finished();
};
and execute with delay...
handler.postDelayed(runnable, MIN_SPLASH_DURATION);
You can use Thread.sleep method
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
You have this way to work with asyntask and 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;
}
}
}
}
@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;
}
Use Thread.sleep() instead of wait()
.