Wenn Sie eine wait
in einer AsyncTask
verwenden, erhalte ich ERROR/AndroidRuntime(24230): Caused by: Java.lang.IllegalMonitorStateException: object not locked by thread before wait()
Kann eine Asynctask
nur zum Warten verwendet werden? Wie?
Vielen Dank
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();
}
}
Verwenden Sie Thread.sleep () anstelle von wait()
.
Sie können die Methode Thread.sleep verwenden
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;
}
Wenn Sie die Ausführung einer Methode nur um eine bestimmte Zeit verschieben möchten, ist Handler.postDelayed () eine gute Option.
definiere den Handler und lauffähig ...
private Handler handler = new Handler();
private Runnable runnable = new Runnable() {
finished();
};
und mit Verzögerung ausführen ...
handler.postDelayed(runnable, MIN_SPLASH_DURATION);
Verwenden Sie dazu Threads
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;
}
bei einem Berührungsereignis wird der Thread benachrichtigt .. kann sich je nach Bedarf ändern.
Sie haben auf diese Weise mit asyntask und wait () zu arbeiten.
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;
}
}
}
}