3

I create an application with lots of fragments . In my last fragment I try to print something on LogCatafter 10 seconds . But it dosen't work for me .

This is my Fragment class

public class StepTwentyTwoFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.step22_fragment, container, false);

        testMethod();
        return v;
    }

    public static StepTwentyTwoFragment newInstance() {

        StepTwentyTwoFragment f = new StepTwentyTwoFragment();
        Bundle b = new Bundle();

        f.setArguments(b);

        return f;
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser) {
            Activity a = getActivity();
            if(a != null) a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    public void testMethod(){
        SystemClock.sleep(10000);
        Log.d("PPP : ","456");
    }

}

Actually I want print this "PPP" after 10 seconds when last fragment is launched. But it begins to print with the loading of some fragments in the application.

Have any ideas about this ?

Thank you.

Terance Wijesuriya
  • 1,928
  • 9
  • 31
  • 61
  • Don't `sleep`. You can use the [`postDelayed`](https://developer.android.com/reference/android/view/View.html#postDelayed%28java.lang.Runnable,%20long%29) method of your `View v` you have in `onCreateView` to schedule a `Runnable` that eventually prints the log message. Or you can use a Handler. – zapl May 25 '16 at 11:19
  • @zapl : explain more with an example. – Terance Wijesuriya May 25 '16 at 11:24

6 Answers6

8

You shouldn't sleep, nor create threads when you don't need them. Android's main thread is event-loop based and you can schedule events / code to be executed at a point in the future.

Your simplest option is to use

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.step22_fragment, container, false);
    Runnable delayedTask = new Runnable() {
        @Override
        public void run() {
            Log.d("PPP : ","456");
        }
    };
    v.postDelayed(delayedTask, 10000);
    return v;
}

If you don't have a View you can also create your own handler.

private static final Handler mainThreadHandler = new Handler(Looper.getMainLooper());
public void testMethod(){
    Runnable delayedTask = new Runnable() {
        @Override
        public void run() {
            Log.d("PPP : ","456");
        }
    };
    mainThreadHandler.postDelayed(delayedTask, 10000);
}
zapl
  • 63,179
  • 10
  • 123
  • 154
6

Use Handler.postDelayed method to achieve this.

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
  @Override
  public void run() {
    //Do something after 10000ms

  }
}, 10000);

Place the code you want to execute in the run() method.Read more about Handlers from here

Abhinav Pawar
  • 421
  • 3
  • 12
2

Probably you are sleeping the ui thread that's why your log appears after sleep ends.

Use Timer and TimerTask. TimerTask runs on a different thread from ui thread.

Timer timer          = new Timer();
TimerTask timer_task = new TimerTask() {
    @Override
    public void run() {
        Log.d("PPP : ","456");
    }
};
timer.schedule(timer_task, 10000);
Burak Day
  • 907
  • 14
  • 28
1

try this

public void executePeriodicTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {       
    @Override
    public void run() {
        handler.post(new Runnable() {
            public void run() {       
                try {

                  //Write your code here , which you want to execute periodically

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                }
            }
        });
    }
};
timer.schedule(doAsynchronousTask, 0, 50000); //execute in every 50000 ms

}

mdDroid
  • 3,135
  • 2
  • 22
  • 34
1

You can simple Create a Thread Or Handler for that.

If you want to use Thread ->

new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {}
        ((Activity)getActivity()).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.d("PPP : ","456");
                // Do other Stuff
            }
        });
    }
}).start();
Zahidul Islam
  • 3,180
  • 1
  • 25
  • 35
1

You can use Handler with PostDelayed passing Runnable to it

 new Handler().postDelayed(new Runnable(){
        @Override
        public void run() {

             Log.d("PPP : ","456");
        }
    }, 10000);
Moh'd Awad
  • 1,758
  • 1
  • 12
  • 22