How to execute a task after a certain time period in Android?

Terance picture Terance · May 25, 2016 · Viewed 7.3k times · Source

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.

Answer

zapl picture zapl · May 25, 2016

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);
}