gpt4 book ai didi

android - 为什么 Handler::postDelayed 会使 UI 卡住

转载 作者:行者123 更新时间:2023-11-29 14:29:07 24 4
gpt4 key购买 nike

我有这个代码。我不知道为什么 postDelay 在这种情况下使 UI 卡住。我希望 Runnable 将在延迟 100 毫秒后运行并在 4000 毫秒后运行。

package com.delaythread;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;

public class MyNeedActivity extends Activity implements OnClickListener {

private ProgressBar progressBar;
private final Handler handler = new Handler() {
@Override
public void handleMessage(final Message msg) {
super.handleMessage(msg);
progressBar.setVisibility(ProgressBar.INVISIBLE);
}
};

@Override
public void onClick(final View v) {
if(v.getId() == R.id.button1) {
/* This call doesn't make ProgressBar frozen.
final Thread t = new Thread(new MyRunnable());
t.start();
progressBar.setVisibility(ProgressBar.VISIBLE);
*/

// This makes ProgressBar frozen in 4000 miliseconds.
final boolean b = handler.postDelayed(new MyRunnable(), 100);
if(b) {
progressBar.setVisibility(ProgressBar.VISIBLE);
}
}
}

/** Called when the activity is first created. */
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button)findViewById(R.id.button1)).setOnClickListener(this);
progressBar = (ProgressBar)findViewById(R.id.progressBar1);
}

private class MyRunnable implements Runnable {
@Override
public void run() {
sleep();
}

private void sleep() {
try {
Thread.sleep(4000);
handler.sendEmptyMessage(0);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
}

}

更新:其实我想要的是AsyncTask在延迟时间后执行,所以我按照这个答案做Java/android how to start an AsyncTask after 3 seconds of delay? .他说我应该使用 Handler 和 Runnable。

最佳答案

根据帖子,以下内容应该符合您的需要

private final Handler handler = new Handler() {
@Override
public void handleMessage(final Message msg) {
super.handleMessage(msg);
//start Asyntask here. progress show/hide should be done in asynctaswk itself.
}
};

@Override
public void onClick(final View v) {
if(v.getId() == R.id.button1) {

final boolean b = handler.postDelayed(new MyRunnable() , 1000);

}
}

private class MyRunnable implements Runnable {
@Override
public void run() {
handler.sendmessage(0);
}
}

}

关于android - 为什么 Handler::postDelayed 会使 UI 卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7038463/

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