Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to And Restart Thread again on Activity Created

What i am doing is Starting a Thread once a button is Clicked inside a fragment and on Back press my Activity and Fragment gets Destroyed but when again that activity and fragment is called i want to again start my thread from its previous state.

I know i am not providing much information but i too am much confused what i am asking for.

So kindly help me.

Here what i am doing know

thread = new Thread(new Runnable() {
    @Override
    public void run() {
        while (runThread) {
            try {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        updateProgress();
                    }
                });
                Thread.sleep(200);
            } 
            catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                break;
            }
        }
    }
});
thread.start();

here is my onDestroy

@Override
public void onDestroyView() {
    // TODO Auto-generated method stub
    super.onDestroyView();
    try {
        if (thread != null) {
            runThread = false;
        } else {

        }
    } 
    catch (Exception e) {
    }
}
like image 327
Ramkesh Yadav Avatar asked Nov 11 '22 01:11

Ramkesh Yadav


1 Answers

It seems that the thread will not stop till it finished.

thread = new Thread(new Runnable() {
    @Override
    public void run() {
        while (runThread) {
            try {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                       //+ Hear
                        if(runStat){                           
                           updateProgress();
                        }
                    }
                });
                Thread.sleep(200);
            } 
            catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                break;
            }
        }
    }
});


@Override
public void onDestroyView() {
    // TODO Auto-generated method stub
    super.onDestroyView();
    try {
        if (thread != null) {
            runThread = false;
            runStat=false;
        } else {

        }
    } 
    catch (Exception e) {
    }
}

@Override
public void onStop() {
    // TODO Auto-generated method stub
    super.onStop();  
    runStat=false;    
}

 @Override  
 protected void onStart() {  
    // TODO Auto-generated method stub  
    super.onStart();  
    runStat=true;  
 } 
like image 102
Patato Avatar answered Nov 15 '22 00:11

Patato