4

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();
Philipp Jahoda
  • 50,880
  • 24
  • 180
  • 187
IAmGroot
  • 13,760
  • 18
  • 84
  • 154
  • Look at : https://stackoverflow.com/questions/8052522/why-we-call-thread-start-method-which-in-turns-calls-run-method/36812010#36812010 – Ravindra babu Nov 24 '17 at 13:17

1 Answers1

27

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.

Philipp Jahoda
  • 50,880
  • 24
  • 180
  • 187
  • 1
    Sigh, I knew it was a silly question. Ironically I wrote a test Thread, and put `start();` That being said, if I hadnt asked, i'd have wasted more hours figuring it out. It does make sense now. Calling `run()` just calling the method on the UI thread, as would calling any method directly. Thanks! – IAmGroot Sep 03 '13 at 14:20
  • 1
    2 year latter and yes, it helped me =D – user2582318 Jul 01 '15 at 21:09