gpt4 book ai didi

android - 从线程传递消息以更新 UI

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:35:52 25 4
gpt4 key购买 nike

我为文件浏览器创建了一个新线程。线程读取目录的内容。我想要做的是更新 UI 线程以绘制文件和文件夹的图形表示。我知道我无法从新线程中更新 UI,所以我想做的是:

当文件扫描线程遍历目录文件和文件夹时,将文件路径字符串传递回 UI 线程。 UI 线程中的处理程序然后绘制传回文件的图形表示。

public class New_Project extends Activity implements Runnable {

private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Log.d("New Thread","Proccess Complete.");
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
};


public void fileScanner(){
//if (!XMLEFunctions.canReadExternal(this)) return;
pd = ProgressDialog.show(this, "Reading Directory.",
"Please Wait...", true, false);

Log.d("New Thread","Called");
Thread thread = new Thread(this);
thread.start();
}


public void run() {
Log.d("New Thread","Reading Files");
getFiles();
handler.sendEmptyMessage(0);
}


public void getFiles() {
for (int i=0;i<=allFiles.length-1;i++){
//I WANT TO PASS THE FILE PATH BACK TU A HANDLER IN THE UI
//SO IT CAN BE DRAWN.
**passFilePathBackToBeDrawn(allFiles[i].toString());**
}
}

}

最佳答案

似乎传递简单消息是基于 int 的...我需要做的是传递一个 Bundle

using Message.setData(Bundle) and Message.getData(Bundle)

好开心=0)

//Function From Within The Thread

public void newProjectCreation() {

Message msg = new Message();
Bundle bundle = new Bundle();

bundle.putString("Test", "test value");
msg.setData(bundle);

handler2.sendMessage(msg);
}

//Handler in The UI Thread Retreieves The Data
//And Can Update the GUI as Required

private Handler handler2 = new Handler() {
@Override
public void handleMessage(Message msg) {

Bundle bundle = msg.getData();
Toast.makeText(New_Project.this,bundle.getString("Test"),Toast.LENGTH_SHORT).show();

}

};

关于android - 从线程传递消息以更新 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4705152/

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