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();
}
}
How would I stop the thread in onCreate from onLocationChanged? I need to stop the progressbar once the GPS provides the coordinates. I need to join the threads using join(). Solution will be helpful.
使timerThread为类成员,而不是语言环境变量,通过这种方式,您应该从onLocationChanged方法访问它
改用AsyncTask,存储Future并自己停止线程。
If this is not a home work assignment, then I see no need to join()
. Even more so when you're trying to join the UI thread with an arbitrary thread, effectively casuing an ANR .
Either:
Create you own class extending Thread
, implement your terminate()
method, and then call it whenever you want.
Create your own class extending AsyncTask , implementing LocationListener, and use its onProgressUpdate() method.
You can simply declare in your Activity a member :
private Thread mTimerThread = null;
then in your onCreate() replace :
final Thread timerThread = new Thread() {
with
mTimerThread = new Thread() {
and in onLocationChanged :
if (mTimerThread != null && mTimerThread.isAlive()) {
mTimerThread.terminate();
}
to achieve what you want.
However, as others mentioned, I would also recommend using custom AsyncTask
as it would be most clear way of threading in your case.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.