我有点困惑,不知道在哪里寻找。我想要的是刷新屏幕文本cn& sn每5秒钟。我怎么能用这个线程来降低它?它是我更新文本字段的唯一场所。我用线程消息/ Handler管理它,但它太长了。那么有什么更短的方式吗?
Thread t = new Thread(){
public void run() {
while(true) {
cn.setText(getClName()); //mutated text
sn.setText(getSN()); //mutated text
Thread.sleep(5 * 1000);
}
}
};
t.start();
我遇到了这种错误:
03-22 09:04:22.669: E/AndroidRuntime(7877): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
03-22 09:04:22.669: E/AndroidRuntime(7877): at android.view.ViewRoot.checkThread(ViewRoot.java:3020)
03-22 09:04:22.669: E/AndroidRuntime(7877): at android.view.ViewRoot.requestLayout(ViewRoot.java:634)
03-22 09:04:22.669: E/AndroidRuntime(7877): at android.view.View.requestLayout(View.java:8267)
03-22 09:04:22.669: E/AndroidRuntime(7877): at android.view.View.requestLayout(View.java:8267)
03-22 09:04:22.669: E/AndroidRuntime(7877): at android.view.View.requestLayout(View.java:8267)
03-22 09:04:22.669: E/AndroidRuntime(7877): at android.view.View.requestLayout(View.java:8267)
03-22 09:04:22.669: E/AndroidRuntime(7877): at
03-22 09:04:28.849: E/global(7877): Deprecated Thread methods are not supported.
03-22 09:04:28.849: E/global(7877): java.lang.UnsupportedOperationException
03-22 09:04:28.849: E/global(7877): at java.lang.VMThread.stop(VMThread.java:85)
03-22 09:04:28.849: E/global(7877): at java.lang.Thread.stop(Thread.java:1280)
03-22 09:04:28.849: E/global(7877): at java.lang.Thread.stop(Thread.java:1247)
03-22 09:04:28.849: E/global(7877): at android.kvisio.Main.onDestroy(Main.java:298)
答案 0 :(得分:4)
这样做,
Thread t = new Thread(){
public void run() {
while(true) {
YouActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
cn.setText(getClName()); //mutated text
sn.setText(getSN()); //mutated text
}
});
Thread.sleep(5 * 1000);
}
}
};
t.start();
您必须始终从UI线程运行UI活动。 ANdroid试图通过提供AsyncTask来帮助开发人员实现这一目标。尽可能多地尝试使用它。如果由于要求而无法使用,请使用runOnUiThread()功能。
答案 1 :(得分:3)
声明类型为Handler
的类成员private Handler uiCallback;
然后,在您的代码中:
uiCallback = new Handler () {
public void handleMessage (Message msg) {
cn.setText(getClName()); //mutated text
sn.setText(getSN()); //mutated text
}
};
Thread t = new Thread(){
public void run() {
while(true) {
uiCallback.sendEmptyMessage(0);
Thread.sleep(5 * 1000);
}
}
};
t.start();
This article解释了您的问题。
答案 2 :(得分:2)
根据当前的Android文档只有UI线程可以更新UI ,但是为了使您的系统正常工作,您可以使用Handler并发送Message来更新UI ...请参阅此{{3 }}
你也可以使用AsyncTask,阅读一个不错的博客question ..
答案 3 :(得分:0)
cn.setText(getClName()); //mutated text
sn.setText(getSN());
这是问题所在。修复你必须修改UI线程的视图。要实现此目的,您可以使用handler
,或者如果您在活动中,则可以使用runOnUiThread(Runnable)