为什么我的Thread会冻结UI-Thread?

Doo*_*ght 4 networking multithreading android freeze ui-thread

我弄清楚了.

出于某种原因,这个线程的代码实际上是在UI线程上运行的.如果我突破它,UI就会停止.或者睡觉吧,UI停了.因此,在"ui"线程中不允许网络活动.

我没有使用过异步任务,因为我不知道循环它的正确方法.(调用它的新实例onPostExecute似乎是不好的做法,好像异步是一个关闭的任务.

我扩展了Thread.

public class SyncManager  extends Thread {

public SyncManager(Context context){
    sdb = new SyncManagerDBHelper(context);
    mContext = context;     
}

@Override
public void run() {     

    while(State == RUNNING) {
        try{
            SyncRecords();   // Break point here = UI freeze.
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            Thread.sleep(10000); // So also causes UI freeze.
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

 public void startThread() {
    Log.i("SyncManager", "start called");

    if((State == PAUSED || State == STOPPED) && !this.isAlive() )
    {
        State = RUNNING;
        run();      
    }   
}   
Run Code Online (Sandbox Code Playgroud)

来自我的活动我打电话

  sm = new SyncManager(this);
  sm.startThread();
Run Code Online (Sandbox Code Playgroud)

Phi*_*oda 26

您应该使用Thread.start()启动任何新线程.据我所知,run()直接调用不会导致系统实际启动新线程,因此阻止UI.

将您的startThread()方法更改为以下,然后它应该工作:

public class SyncManager extends Thread {

    public void startThread() {

        if((State == PAUSED || State == STOPPED) && !this.isAlive()) {
            State = RUNNING;
            start();  // use start() instead of run()
        }   
    }
}
Run Code Online (Sandbox Code Playgroud)

请阅读此处以获取Java重访博客中的更多具体信息.