Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my Thread freeze the UI-Thread?

I cant figure it out.

For what ever reason, this thread's code is actually running on the UI thread. If i break point it the UI stops. or Sleep it, UI stopped. and hence network activity is unallowed as its on the "ui" thread.

Ive not used Async task, because I am unaware of the proper way of looping it. (calling a new instance of it in onPostExecute seems like bad practice, and as if async is for one off tasks.

I extend 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();      
    }   
}   

ANd from my Activity I call

  sm = new SyncManager(this);
  sm.startThread();
like image 282
IAmGroot Avatar asked Nov 28 '22 17:11

IAmGroot


1 Answers

You should use Thread.start() to start any new thread. As far as I know calling run() directly will not cause the system to actually launch a new thread, hence your blocking UI.

Change your startThread() method to the following and it should then work:

public class SyncManager extends Thread {

    public void startThread() {

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

Read here for more specific information from the Java revisited blog.

like image 152
Philipp Jahoda Avatar answered Dec 03 '22 06:12

Philipp Jahoda