android - Cannot figure out why handler thread is not working
问题描述
I was learning the handler thread and I got an issue. It's not working. I gave delay of 3 sec with postDelayed and also used postAtTime but none is working now. And there is no eeror or exception in run tab either.
here is the java code.
package com.example.ims;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.ProgressBar;
import androidx.appcompat.app.AppCompatActivity;
public class SplashScreen extends AppCompatActivity {
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
init();
int interval = 3000;
new Handler(Looper.getMainLooper()).postAtTime(new Runnable(){
@Override
public void run() {
progressBar.setVisibility(View.VISIBLE);
}
},System.currentTimeMillis()+ interval);
}
void init()
{
progressBar = findViewById(R.id.progressbar);
progressBar.setVisibility(View.GONE);
}
@Override
protected void onStart() {
super.onStart();
}
}
This code should show progressbar after 3 seconds but, it's not showing.
I have gone through these links, But none helped me
Android threading and Handler not working
I visited some other links too. But, Apparantly all are concluding that handler thread should be in onCreate() method, But mine is already in onCreate method.
解决方案
for using postDelayed() you must do this:
int interval = 3000;
new Handler(Looper.getMainLooper()).postDelayed(new Runnable(){
@Override
public void run() {
progressBar.setVisibility(View.VISIBLE);
}
},interval);
but for using postAtTime() you must use SystemClock.uptimeMillis() instead of System.currentTimeMillis(). Because second parameter of postAtTime() get uptime millis and not current time millis.
postAtTime() doc say about it second parameter:
"The absolute time at which the callback should run, using the {@link android.os.SystemClock#uptimeMillis} time-base"
推荐阅读
- python - 在 Python 中调用模拟方法的类的测试实例
- python - pytest 在没有 pytest.ini 文件的情况下从 shell 调用时忽略 venv
- sql - SQL优化分享邮编和号码
- node.js - 在 Node.js 中,为什么管道到 child_process.stdout 到 process.stdout 会去除 ANSI 颜色?
- datatables - 获取计数最高的项目
- amazon-web-services - 如何在 Kubernetes 提供商计划中引用 AWS 提供商计划的输出?
- python - C++ 从向量效率问题中删除
- java - 在给定时间内更改类的属性
- azure-devops - Azure Devops Docker Compose 构建
- bash - Sed:尝试将搜索到的组转换为 shell 执行以格式化输出