java如何加入线程以停止它?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mProgressBar = (ProgressBar)findViewById(R.id.adprogress_progressBar);
final Thread timerThread = new Thread() {
private volatile boolean running = true;
public void terminate() {
running = false;
}
@Override
public void run() {
while(running) {
mbActive = true;
try {
int waited = 0;
while(mbActive && (waited < TIMER_RUNTIME)) {
sleep(200);
if(mbActive) {
waited += 200;
updateProgress(waited);
}
}
} catch(InterruptedException e) {
running=false;
}
}
}
};
timerThread.start();
}
public void onLocationChanged(Location location) {
if (location != null) {
TextView text;
text = (TextView) findViewById(R.id.t2);
String str= "Latitude is " + location.getLatitude() + "\nLongitude is " + location.getLongitude();
text.setText(str);
text.postInvalidate();
}
}
如何停止onCreate from onLocationChanged中的线程?一旦GPS提供了坐标,我需要停止progressbar。我需要使用join()连接线程。解决方案将是有益的
# 1 楼答案
如果这不是家庭作业,那么我认为没有必要
join()
。更重要的是,当您试图将UI线程与任意线程连接时,实际上会导致ANR要么:
创建自己的类扩展
Thread
,实现terminate()
方法,然后随时调用它创建自己的类,扩展AsyncTask,实现LocationListener,并使用其onProgressUpdate()方法
# 2 楼答案
您只需在活动中声明成员:
然后在onCreate()替换中:
与
在onLocationChanged中:
实现你想要的
然而,正如其他人提到的,我还建议使用自定义
AsyncTask
,因为在您的情况下,这是最清晰的线程方式# 3 楼答案
改为使用AsyncTask,存储未来并自己停止线程
# 4 楼答案
使timer读取类成员而不是区域设置变量,这样您应该从onLocationChanged方法访问它