作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
基本上,我正在尝试运行一个秒计数器和一个级别计数器。每 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/
我是一名优秀的程序员,十分优秀!