简体   繁体   English

从按下按钮开始,每秒运行一次方法

[英]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 每当再次按下时,计时器都会重置为0,然后再次开始递增

I know this isn't the way to do it, the button works fine but the timer should be in onCreate? 我知道这不是这样做的方法,按钮可以正常工作,但计时器应该在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 另一个简单的方法是使用Handler

mHandler = new Handler();

Just call updateSec(); 只需调用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. 视图必须在主线程上更新,因此您需要使用具有可运行实例作为参数的post()方法。

Alternatively, you can also use AsyncTask. 或者,您也可以使用AsyncTask。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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