Pregunta

Hello i'm new in Android(Java), and i have a problem with the use of thread

I define e new Thread timed (every 5 seconds) inside a class of my android Project. The "mContinueThread" variable is used to cicle every 5 seconds

r = new Runnable() {
    public void run() {
        while (mContinueThread) {
            try {
                Thread.sleep(MILLISEC_BEFORE_RELOAD);
                mHandler.sendEmptyMessage(GET_TRACKING);
            }
            catch (Exception e)
            {

            }
        }
    }
};
t = new Thread(r);

In the CLass there is a method StartTrack() that starts with Thread

public void StartTrack()
{
    mContinueThread=true;
    if (!mThreadIsStarted)
    {
        mThreadIsStarted=true;
        t.start();
    }
    else
    {

    }
}

and there is also a method Logout that stop the thread, using the "mContinueThread" variable:

public void LogOut()
{
    //STOP THREAD
    mContinueThread=false;
    ....
}

If in the class Logout() method is executed the thread is stopped, but if the StartTrack() method is called again I don't know how to restart the execution of the thread.

Can you Help Me?

¿Fue útil?

Solución 4

I solved so:

In my class I just define the Runnable object, but not the new Thread.

In the StartTrack method(), if the thread has not yet been instantiated, I create and start

public void StartTrack()
{
    mContinueThread=true;

    if (!mThreadIsStarted)
    {
        mThreadIsStarted=true;
        t = new Thread(r);
        t.start();
    }
}

In the "LogOut()" method, if Thread is started, I Stop It, and I set It to Null.

In this way, at the next call of "StartTrack()" method, I can recreate it again

public void LogOut()
{
    mContinueThread=false;
    if (mThreadIsStarted)
    {
        //THREAD STOP
        mContinueThread=false;
        mThreadIsStarted=false;

        //THREAD TO NULL
        t=null;
    }

    ...
}

Otros consejos

You can use AsyncTask in Android. This will get rid of the burden of managing the threads manually. Please visit http://developer.android.com/reference/android/os/AsyncTask.html

You cannot re-start a thread. Once thread is finished execution it will reach the DEAD state. And whatever is DEAD cannot be brought back to life again, neither in real world nor in JAVA world.

You have no way to restart a thread as long as it exited. You can just start a new start.

I suggest it's better to use something like Timer instead of thread.

http://developer.android.com/reference/java/util/Timer.html

Then you can do cancel() if you want to stop execution of your task and resume it by scheduling new one.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top