大家好,我是android应用程序开发的新手。我编写并编写代码并尝试从处理程序获取的消息更新UI。我试图调试代码,但我找不到错误是什么。请帮帮我。谢谢。
package com.threadcommunicationexample;
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.TextView;
public class MainActivity extends Activity implements OnClickListener {
Button Click;
TextView Message;
Handler Mrmessenger;
int Counter = 0;
/*
*Initialisation area....
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Click = (Button) findViewById(R.id.ClickButton);
Message = (Button) findViewById(R.id.TextView);
Click.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// Operation to be performed after the button click
Runnable myThreadRunner = new Runnable() {
@Override
public void run() {
// Saving the text in bundle and passing it to handler ....
while (Counter < 100) {
try {
Thread.sleep(100);
Message msg = Mrmessenger.obtainMessage();
Bundle myBundle = new Bundle();
myBundle.putString("Communication", "Loading....");
msg.setData(myBundle);
//Sending the bundle to Handler
Mrmessenger.sendMessage(msg);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Mrmessenger = new Handler() {
public void handleMessage(final Message msg) {
Mrmessenger.post(new Runnable() {
// Getting the message from the handler and updating it using textview
@Override
public void run() {
Bundle ComBundle = msg.getData();
// TODO Auto-generated method stub
String myMessage = ComBundle
.getString("Communication");
Message.setText(myMessage);
}
});
}
};
Counter++;
}
}
};
Thread myRunner = new Thread(myThreadRunner);
//creating a thread and passing the runnable object.
myRunner.start();
}
}
答案 0 :(得分:1)
您的代码的问题是,处理程序中的run方法是在除main / ui线程之外的另一个线程上调用的。 要使代码正常工作,您可以使用以下代码..
runOnUiThread(new Runnable() {
public void run() {
Message.setText(myMessage);
}
});
..在ui线程上显式运行ui更新。
答案 1 :(得分:1)
一方面,这条线
Message msg = Mrmessenger.obtainMessage();
将失败,因为您在几行之后才初始化Mrmessenger
。
建议你使用AsyncTask
来做这类事情;它处理所有线程,所以你不需要。
另外:根据Java约定,变量名称应以小写字母开头,类名称以大写字母开头。这将使您的代码更容易让其他人阅读。