1

I am trying to call my takepicture() method after every 1 minute. So, I tried using the handler class and then tried calling my method within its run function. However, when I tried doing a step wise debugging, it never enters the run method at all. Can anyone please suggest me what I am doing wrong? I am trying to call it from my fragment.

@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mFile = new File(getActivity().getExternalFilesDir(null), "pic.jpg");
        final Handler handler = new Handler();

        final Runnable r = new Runnable() {
            public void run() {
                Log.d("HandlerThread","This is from the HandlerThread");
            takePicture();
            handler.postDelayed(this, 60000);
            }
        };


    }
Shubhamhackz
  • 7,333
  • 7
  • 50
  • 71
Monica Das
  • 157
  • 11

3 Answers3

2

You never call any method that would run the Runnable. You only specified its behavior inside the run() function.

In order to start the Runnable, call something like handler.postDelayed(r, 0);


Just an info: please note that your Handler is still tied to the main Thread. See this answer and this one if you want to run it on a separate thread.

payloc91
  • 3,724
  • 1
  • 17
  • 45
2

Try this:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mFile = new File(getActivity().getExternalFilesDir(null), "pic.jpg");
    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        public void run() {
            Log.d("HandlerThread","This is from the HandlerThread");
        takePicture();
        }
    }, 60000);
}

Rather than defining the handler.postDelayed within run method.I have just changed the call within your main thread itself.

Kindly mark it as answer if it solves your problem.

Saurabh7474
  • 450
  • 5
  • 12
0

You should make an initial call to start the handler functionality. ie , handler.post(r);

Febi M Felix
  • 2,799
  • 1
  • 10
  • 13