简体   繁体   中英

Running a method every second starting on button press

I need a timer to start any time I press a button (on the button itself) that shows how many seconds it's been since it's pressed in real time. Whenever it's pressed again, timer is reset to 0 and starts incrementing again

I know this isn't the way to do it, the button works fine but the timer should be in onCreate? I'm not sure how this is supposed to work with a button

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        downloadedImg = (ImageView) findViewById(R.id.imageView);
    }

    public void clickAsync(View view) {

            new ImageDownloader().execute(downloadUrl);
            int seconds = 0;
            Button button = (Button) view;

            button.setText("Seconds since clicked: " + seconds);
            Timer timer = new Timer();

            //each time button is clicked, time is reset to 0 and increments in real time
            timer.scheduleAtFixedRate(new TimerTask()
            {
                public void run()
                {
                    seconds = 0;
                    seconds++;
                    button.setText("Seconds since clicked: " + seconds);
                }
            }, 0, 1000);
      }
}

try this: use a handler

 long startTime = 0;
 long elapsedTime ;

//runs without a timer by reposting this handler at the end of the runnable
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {

    @Override
    public void run() {
        long millis = System.currentTimeMillis() - startTime;
        int seconds = (int) (millis / 1000);
        int minutes = seconds / 60;
        int hours = minutes / 60;
        seconds = seconds % 60;
        //textview for displaying time..
        timerTextView.setText(String.format("%d:%02d:%02d", hours, minutes, seconds));

        timerHandler.postDelayed(this, 1000);
    }
};

 b.setOnClickListener(new View.OnClickListener() { //b is your button

    @Override
    public void onClick(View v) {
        Button b = (Button) v;
        if (b.getText().equals("Stop")) {
            elapsedTime = System.currentTimeMillis() - startTime;
            timerHandler.removeCallbacks(timerRunnable);
            b.setText("Resume");
        } else {
            startTime = System.currentTimeMillis() - elapsedTime;
            timerHandler.postDelayed(timerRunnable, 0);
             Calendar cs = Calendar.getInstance();
            System.out.println("Current time => " + cs.getTime());
            SimpleDateFormat df = new SimpleDateFormat("HH:mm");
            String formattedDate = df.format(cs.getTime());
            timerTextView.setText(formattedDate);
            b.setText("Stop");
        }
    }
});

it will calculate the elapsed time and show time after stop...

Another easy way to do this is to use Handler

mHandler = new Handler();

Just call updateSec(); method on click of a button it'll update sec in interval of one seconds

Runnable UpdateRunnable = new Runnable() {

    @Override
    public void run() {
        updateSec();
    }
};

    public void updateSec() {
          mSeconds++;
          mHandler.postDelayed(UpdateRunnable, 1000);
     }

Example

button.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
    mSeconds = 0;
    updateSec();//it'll update sec variable every second.
  }
});

You can use threads:

@Override
public void onClick(View view){
switch(view.getId()){
case R.id.button:
new Thread(new Runnable() {
@Override
public void run() {
try{
Thread.sleep(1000);
} catch(InterruptedException e) {
e.printStackTrace();
}
count++;
textView.post(new Runnable() {
@Override
public void run() {
textView.setText(count + "");
}
});
}
}
}).start;
break;
}
}

the view must be updated on main thread, and so you need to use post() method that has runnable instance as parameter.

Alternatively, you can also use AsyncTask.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM