Question

I want to make a program which will tell me the number of seconds I kept holding the button.

for example if I clicked the button for 5 seconds, it should tell me the button remained pressed for 5 seconds.

is this achievable in android?

This is how I tried, didn't work because when I put the while loop in, the button stays clicked even I press it for just one second. The program doesn't crash but the button remains clicked and I think it freezes.

 thread = new HandlerThread("");



    btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            while(btn.isPressed())
            {

                try {
                    thread.sleep(1000);
                    total = total++;
                    temp = temp++;
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            Toast.makeText(MainActivity.this, ""+temp+" "+total, 0).show();


        }
    });
Was it helpful?

Solution

You could use time stamps, and an OnTouchListener to achieve this.

When your OnTouchListener receives an ACTION_DOWN event, store the first time stamp. When it receives an ACTION_UP event, store the second time stamp and calculate the difference between the two.

As mentioned by Raghunandan, you should never block on the UI thread using calls such as thread.sleep, as this will cause the UI to stop responding, and in some cases can cause the program to be killed because of this.

Here is an example of what I've outlined above. Please note, this code was written from memory, and has not been tested, but you should get the general gist of it.

btn.setOnTouchListener(new OnTouchListener() {
    private long firstTouchTS = 0;
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction()==MotionEvent.ACTION_DOWN) {
            this.firstTouchTS = System.currentTimeMillis();
        } else if (event.getaction()==MotionEvent.ACTION_UP) {
            Toast.makeText(MainActivity.this,((System.currentTimeMillis()-this.firstTouchTS)/1000)+" seconds",0).show();
        }
    }
});

References: OnTouchListener MotionEvent

OTHER TIPS

thread.sleep(1000);

Calling sleep on the ui thread hence it freezes. Do not call sleep on the ui thread. It blocks the ui thread.

Read

http://developer.android.com/training/articles/perf-anr.html.

Use a Handler if you want to repeat some task

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top