Using wait in AsyncTask

前端 未结 6 1533
逝去的感伤
逝去的感伤 2021-02-01 01:15

When using a wait in an AsyncTask, I get ERROR/AndroidRuntime(24230): Caused by: java.lang.IllegalMonitorStateException: object not locked by thr

6条回答
  •  南方客
    南方客 (楼主)
    2021-02-01 01:50

    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.

提交回复
热议问题