gpt4 book ai didi

Android,创建一个简单的线程来更新我的秒数计数器

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

基本上,我正在尝试运行一个秒计数器和一个级别计数器。每 10 秒我就想++level。
但这还没有实现,到目前为止,我只是想显示秒数,但我遇到了运行时异常和崩溃。
谷歌搜索我看到它是因为我试图从我的线程更新 UI 而那是不允许的。所以我想我将需要 asyncTask,但我不知道如何使用我的简单小程序来做到这一点。请帮助或给我一些替代方案...

package com.ryan1;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class main extends Activity {

int level = 1;
int seconds_running=0;

TextView the_seconds;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
the_seconds = (TextView) findViewById(R.id.textview_seconds);



Thread thread1 = new Thread(){
public void run(){
try {
sleep(1000); Log.d("RYAN", " RYAN ");

updated_secs();
} catch (Exception e) {
e.printStackTrace();
Log.d("RYAN", " "+e);
}
}
};
thread1.start();
}

public void updated_secs(){
seconds_running++;
the_seconds.setText(" "+seconds_running);
}
}

最佳答案

在您的 UI 线程中创建一个处理程序,然后在工作线程中向处理程序发送消息 (Handler.sendMessage(...))。

消息将在您的 UI 线程上处理,因此您可以正确更新文本小部件。像这样:

private Handler myUIHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
if (msg.what == some_id_you_created)
{
//Update UI here...
}
}
};

Then in your thread, to send a message to the handler you do this:

Message theMessage = myHandler.obtainMessage(some_id_you_created);
myUIHandler.sendMessage(theMessage);//Sends the message to the UI handler.

关于Android,创建一个简单的线程来更新我的秒数计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5371890/

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