gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 07:31:15 24 4
gpt4 key购买 nike

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 allow = false
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

最佳答案

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

关于android - Android Studio Timer任务在启动时使应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61123462/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com