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();
}
}
我将如何停止线程创建从位置更改?一旦GPS提供坐标,我需要停止进度条。我需要使用 join() 连接线程。解决方案将有所帮助。
您可以简单地在活动中声明成员:
private Thread mTimerThread = null;
然后在您的onCreate()中替换:
final Thread timerThread = new Thread() {
跟
mTimerThread = new Thread() {
并在位置更改:
if (mTimerThread != null && mTimerThread.isAlive()) {
mTimerThread.terminate();
}
实现你想要的。
但是,正如其他人提到的,我也建议使用自定义AsyncTask
因为这将是您情况下最清晰的线程方式。
使 timerThread 成为类成员而不是语言环境变量,这样你应该从 onLocationChanged 方法访问它
改用 AsyncTask,存储 Future 并自行停止线程。
如果这不是家庭作业,那么我认为没有必要join()
.当您尝试使用任意线程加入 UI 线程时更是如此,从而有效地引发了 ANR。
也:
-
创建自己的类扩展
Thread
,实现terminate()
方法,然后随时调用它。 -
创建自己的类扩展 AsyncTask,实现 LocationListener,并使用其 onProgressUpdate() 方法。