作为我学习Android线程的一部分,我已完成以下代码。
package simple.learning.com.samplethread;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
MyThread myThread;
Button button;
private static class MyThread extends Thread {
public Handler mHandler;
public void run () {
Log.d ("TESTME", " iNSIDE RUN..");
Looper.prepare();
mHandler = new Handler () {
public void HandleMessage (Message msg) {
Log.d("TESTME", "iNSIDE HandleMessage");
if ( msg.what == 0) {
someWork();
}
}
};
Looper.loop();
}
public void someWork()
{
while (true) {
Log.d("TESTME", "Inside someWork ");
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myThread = new MyThread();
myThread.start();
Button btn = (Button) findViewById(R.id.button1);
assert btn != null;
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (myThread.mHandler != null) {
Log.d("TESTME", " bUTTON pRESSED..");
Message msg = myThread.mHandler.obtainMessage(0);
myThread.mHandler.sendMessage(msg);
}
}
});
}
}
当我单击按钮时,我希望将msg发布到消息队列中。但是,我没有看到任何输出显示。任何帮助将不胜感激。
答案 0 :(得分:1)
你在覆盖handleMessage时犯了一个小错误,而不是覆盖你添加了一些方法的真实错误。以下是工作解决方案:
private static class MyThread extends Thread {
public Handler mHandler;
public void run() {
Log.d("TESTME", " iNSIDE RUN..");
Looper.prepare();
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Log.d("TESTME", "iNSIDE HandleMessage");
if (msg.what == 0) {
someWork();
}
}
};
Looper.loop();
}
public void someWork() {
while (true) {
Log.d("TESTME", "Inside someWork ");
}
}
}