Android Studio Timer任务在启动时使应用程序崩溃

问题描述 投票:0回答:1
public class MainActivity extends AppCompatActivity {



private TextView timerTextView;
private Button pauseStartBtn;
private Button resetBtn;
private Button productiveBtn;
private CountDownTimer countDownTimer;


private Boolean run;
Timer timer = new Timer();
private long timeMS = 0;
private long seconds = 0;
private long minutes = 0;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    timerTextView = findViewById(R.id.timerTextView);
    pauseStartBtn = findViewById(R.id.pauseStartBtn);
    resetBtn = findViewById(R.id.resetBtn);
    productiveBtn = findViewById(R.id.productiveBtn);

    startUp();


}

TimerTask taskUp = new TimerTask() {
    @Override
    public void run() {
        if (run){
            timeMS++;
            seconds = 0;
            minutes = timeMS / 60;
            if (timeMS < 60) {
                seconds = timeMS;
            } else seconds = timeMS - minutes * 60;

            String form = String.format("%02d:%02d", minutes, seconds);

            timerTextView.setText(form);

        }
    }
};

public void startUp(){
    timer.scheduleAtFixedRate(taskUp,1000,1000);// change period back to 1000
}

}

无论如何,这是我运行应用程序时都会崩溃的全部代码。

[如果有问题,我尝试创建的应用是各种天文钟,当我按下按钮时,它会使用我从天文钟获得的时间来运行计时器,并且一旦计时器达到00:00,它就会继续作为计时器,我将其转换为计时器,依此类推。

我仍处于起步阶段,但我想做的是使用TimerTask创建基本的计时器,由于某种原因,当我运行该应用程序时,它会崩溃。非常感谢您的帮助!

编辑:

原木猫

2020-04-09 18:25:46.428 5761-5870 /? D / PowerKeeper.AppBgIdle:setUidState,uid = 10298允许=假2020-04-09 18:25:50.569 4911-4911 /? W / AppStateLoggerT:类型= 1400审核(0.0:66626):AVC:拒绝{读取}名称=“ osrelease” dev =“ proc” ino = 6324986 scontext = u:r:untrusted_app_27:s0:c165,c256,c512, c768 tcontext = u:object_r:proc:s0 tclass =文件许可= 0

android timer crash timertask chronometer
1个回答
0
投票

TimerTask回调是在主(UI)线程上执行的,而UI调用,例如setText,则需要在UI线程上。您应该将对setText的调用包装在对timerTextView.post(...)的调用中,以便在UI线程上调用它。

© www.soinside.com 2019 - 2024. All rights reserved.