我有这个代码:
package org.example.Threading;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ThreadingActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
private doinback background = new doinback();
Handler handle= new Handler(){
@Override
public void handleMessage(Message msg) {
Log.e("INSIDE HANDLER", "About to stop the thread.");
background.stopThread();
}};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.e("ONCREATE", "BEFORE Thread");
background.start();
Log.e("ONCREATE", "AFTER Thread started");
View button = (Button)findViewById(R.id.button1);
button.setOnClickListener(this);
}
class doinback extends Thread{
private volatile boolean isRunning = false;
public void run() {
while(isRunning){
Log.e("INSIDE THREAD", "about to sleep");
handle.sendMessage(handle.obtainMessage());
}
}
public void stopThread()
{
isRunning = false;
}
public void startThread(){
Log.e("INSIDE StartThread","MAKING isRunning True");
isRunning = true;
}
}
public void onClick(View v) {
background.startThread();
Log.e("INSIDE ONCLICK", "made isRunning true, about to leave");
}
}
我试图理解为什么它不回到线程,如果我做错了什么,如果是这样,从线程来回返回的最佳方法是什么,例如我更改的 stopThread() 函数用于停止线程运行的 while 变量的值。当我运行代码并按下按钮时,它不会启动线程。任何想法为什么?